/**
 * PersonalizeWP Product Collection - Collection Picker Component
 *
 * @package PersonalizeWP
 */

import { __ } from '@wordpress/i18n';
import {
	Button,
	Modal,
	Flex,
	FlexItem,
	Icon,
	Card,
	CardBody,
	Tooltip,
} from '@wordpress/components';
import { useState, useCallback, useMemo } from '@wordpress/element';
import {
	seen as viewedIcon,
	starFilled as recommendedIcon,
} from '@wordpress/icons';

const COLLECTION_CARDS = [
	{
		name: 'previously-viewed',
		title: __('Previously Viewed Products', 'personalizewp'),
		icon: viewedIcon,
		description: __('Display products that visitors have recently browsed on your store', 'personalizewp'),
		details: __('Creates a "Recently Viewed" section showing products the current visitor has looked at before. Perfect for helping customers continue their shopping journey.', 'personalizewp'),
		keywords: ['viewed', 'history', 'recent'],
		color: '#7c3aed',
		gradient: 'linear-gradient(135deg, #7c3aed 0%, #a855f7 100%)',
	},
	{
		name: 'products-for-you',
		title: __('Products For You', 'personalizewp'),
		icon: recommendedIcon,
		description: __('Personalized product recommendations based on visitor segments and behavior', 'personalizewp'),
		details: __('Shows tailored product recommendations using PersonalizeWP\'s visitor segments and behavioral data. Displays products from relevant categories and frequently bought together items.', 'personalizewp'),
		keywords: ['recommended', 'personalized', 'segments'],
		color: '#059669',
		gradient: 'linear-gradient(135deg, #059669 0%, #10b981 100%)',
	},
];

function CollectionButton({ collection, onSelect, isSelected = false }) {
	const handleClick = useCallback(() => {
		onSelect(collection.name);
	}, [collection.name, onSelect]);

	const buttonStyle = useMemo(() => ({
		'--collection-color': collection.color,
		'--collection-gradient': collection.gradient,
	}), [collection.color, collection.gradient]);

	return (
		<Tooltip text={collection.details} placement="top">
			<button
				type="button"
				className={`components-button wc-blocks-product-collection__collection-button ${isSelected ? 'is-selected' : ''}`}
				onClick={handleClick}
				style={buttonStyle}
				aria-pressed={isSelected}
				aria-describedby={`collection-${collection.name}-description`}
			>
				<div className="wc-blocks-product-collection__collection-button-icon">
					<Icon icon={collection.icon} size={24} />
				</div>
				<p
					className="wc-blocks-product-collection__collection-button-title"
					id={`collection-${collection.name}-description`}
				>
					{collection.title}
				</p>
			</button>
		</Tooltip>
	);
}

function CollectionPickerModal({ isOpen, onClose, onSelect, currentCollection }) {
	const [selectedCollection, setSelectedCollection] = useState(currentCollection);

	const handleSelect = useCallback(() => {
		if (selectedCollection) {
			onSelect(selectedCollection);
			onClose();
		}
	}, [selectedCollection, onSelect, onClose]);

	const handleCollectionSelect = useCallback((collectionName) => {
		setSelectedCollection(collectionName);
	}, []);

	const isSelectionValid = Boolean(selectedCollection);

	return (
		<Modal
			className="wc-blocks-product-collection__modal pwp-collection-picker-modal"
			onRequestClose={onClose}
			size="large"
			shouldCloseOnClickOutside={false}
			title={__('What products do you want to show?', 'personalizewp')}
		>
			<div className="wc-blocks-product-collection__content">
				<div className="wc-blocks-product-collection__collections-grid">
					<div className="wc-blocks-product-collection__collections-section">
						{COLLECTION_CARDS.map((collection) => (
							<CollectionButton
								key={collection.name}
								collection={collection}
								onSelect={handleCollectionSelect}
								isSelected={selectedCollection === collection.name}
							/>
						))}
					</div>
				</div>

				<Flex className="wc-blocks-product-collection__footer" justify="flex-end" gap={3}>
					<FlexItem>
						<Button
							variant="tertiary"
							onClick={onClose}
						>
							{__('Cancel', 'personalizewp')}
						</Button>
					</FlexItem>
					<FlexItem>
						<Button
							variant="primary"
							onClick={handleSelect}
							disabled={!isSelectionValid}
						>
							{__('Continue', 'personalizewp')}
						</Button>
					</FlexItem>
				</Flex>
			</div>
		</Modal>
	);
}

function CollectionPickerPlaceholder({ onOpenModal }) {
	return (
		<div className="pwp-collection-picker-placeholder">
			<Card>
				<CardBody>
					<div className="pwp-collection-picker-placeholder__content">
						<h3 className="pwp-collection-picker-placeholder__title">
							{__('PersonalizeWP Product Collection', 'personalizewp')}
						</h3>
						<p className="pwp-collection-picker-placeholder__description">
							{__('Create personalized product collections that adapt to each visitor. Choose between showing recently viewed products or segment-based recommendations.', 'personalizewp')}
						</p>
						<Button
							variant="primary"
							onClick={onOpenModal}
							className="pwp-collection-picker-placeholder__button"
						>
							{__('Choose Recipe', 'personalizewp')}
						</Button>
					</div>
				</CardBody>
			</Card>
		</div>
	);
}

function SelectedCollectionDisplay({ collection, onChangeCollection }) {
	const collectionData = useMemo(() =>
		COLLECTION_CARDS.find(c => c.name === collection),
		[collection]
	);

	if (!collectionData) {
		return null;
	}

	return (
		<Card className="pwp-selected-collection">
			<CardBody>
				<Flex direction="column" gap={2}>
					<FlexItem>
						<Flex justify="space-between" align="center">
							<FlexItem>
								<h4 className="pwp-selected-collection__title">
									{collectionData.title}
								</h4>
							</FlexItem>
							<FlexItem>
								<Button
									variant="tertiary"
									size="small"
									onClick={onChangeCollection}
									className="pwp-selected-collection__change-button"
								>
									{__('Change', 'personalizewp')}
								</Button>
							</FlexItem>
						</Flex>
					</FlexItem>
					<FlexItem>
						<p className="pwp-selected-collection__description">
							{collectionData.description}
						</p>
					</FlexItem>
				</Flex>
			</CardBody>
		</Card>
	);
}

export default function CollectionPicker({ currentCollection, onCollectionChange }) {
	const [isModalOpen, setIsModalOpen] = useState(false);

	const handleOpenModal = useCallback(() => {
		setIsModalOpen(true);
	}, []);

	const handleCloseModal = useCallback(() => {
		setIsModalOpen(false);
	}, []);

	const handleCollectionSelect = useCallback((collection) => {
		onCollectionChange(collection);
		handleCloseModal();
	}, [onCollectionChange, handleCloseModal]);

	return (
		<>
			{currentCollection ? (
				<SelectedCollectionDisplay
					collection={currentCollection}
					onChangeCollection={handleOpenModal}
				/>
			) : (
				<CollectionPickerPlaceholder onOpenModal={handleOpenModal} />
			)}

			{isModalOpen && (
				<CollectionPickerModal
					isOpen={isModalOpen}
					onClose={handleCloseModal}
					onSelect={handleCollectionSelect}
					currentCollection={currentCollection}
				/>
			)}
		</>
	);
}
