import { useState, useEffect, useRef } from 'react';
import { CheckCheck } from 'lucide-react';
import { getWordPressConfig } from '@/api/client';

/**
 * CheckIcon Component - renders check-check icon with dynamic color based on completion state
 */
const CheckIcon = ({ isCompleted }) => (
	<CheckCheck
		className="transition-all duration-300"
		size={24}
		color={
			isCompleted
				? 'var(--color-magenta-500)'
				: 'var(--color-neutral-300)'
		}
	/>
);

/**
 * AnimatedTaskList Component
 *
 * Displays an animated checklist with sequential item completion.
 * When canComplete is false, the checklist loops: all items light up,
 * then reset, and start again — until canComplete becomes true.
 *
 * @param {Array<{id: number|string, label: string, delay: number}>} tasks
 * @param {Function} [onComplete] - Called when the animation finishes (only when canComplete is true)
 * @param {boolean} [canComplete=true] - If false, the checklist loops until it becomes true
 * @param {string} [className]
 */
const AnimatedTaskList = ({
	tasks = [],
	onComplete,
	canComplete = true,
	className = '',
}) => {
	const [completedTasks, setCompletedTasks] = useState([]);
	const timeoutsRef = useRef([]);
	const canCompleteRef = useRef(canComplete);
	const onCompleteRef = useRef(onComplete);
	const hasCalledComplete = useRef(false);
	const runCycleRef = useRef(null);

	useEffect(() => {
		canCompleteRef.current = canComplete;
		onCompleteRef.current = onComplete;
	});

	useEffect(() => {
		const clearTimeouts = () => {
			timeoutsRef.current.forEach(clearTimeout);
			timeoutsRef.current = [];
		};

		const finish = () => {
			if (!hasCalledComplete.current) {
				hasCalledComplete.current = true;
				onCompleteRef.current?.();
			}
		};

		const runCycle = () => {
			clearTimeouts();
			setCompletedTasks([]);

			const newTimeouts = tasks.map((task) =>
				setTimeout(() => {
					setCompletedTasks((prev) => [...prev, task.id]);
				}, task.delay)
			);

			const totalTime =
				Math.max(...tasks.map((t) => t.delay)) + 1000;
			newTimeouts.push(
				setTimeout(() => {
					if (canCompleteRef.current) {
						finish();
					} else {
						runCycle();
					}
				}, totalTime)
			);

			timeoutsRef.current = newTimeouts;
		};

		runCycleRef.current = runCycle;

		if (tasks.length > 0) {
			runCycle();
		}

		return clearTimeouts;
	}, [tasks]);

	// If canComplete becomes true and all tasks are already lit, finish now
	useEffect(() => {
		if (
			canComplete &&
			completedTasks.length === tasks.length &&
			tasks.length > 0 &&
			!hasCalledComplete.current
		) {
			hasCalledComplete.current = true;
			timeoutsRef.current.forEach(clearTimeout);
			timeoutsRef.current = [];
			const t = setTimeout(() => onCompleteRef.current?.(), 600);
			timeoutsRef.current = [t];
		}
	}, [canComplete, completedTasks.length, tasks.length]);

	return (
		<div
			className={`space-y-5 ${className}`}
			role="status"
			aria-live="polite"
		>
			{tasks.map((task) => {
				const isCompleted = completedTasks.includes(task.id);

				return (
					<div
						key={task.id}
						className="flex items-center gap-4 transition-all duration-300"
					>
						<div className="flex items-center justify-center w-6 h-6 flex-shrink-0">
							<CheckIcon isCompleted={isCompleted} />
						</div>
						<span
							className={`paragraph-medium transition-all duration-300 ${
								isCompleted
									? 'text-magenta-500'
									: 'text-neutral-300'
							}`}
						>
							{task.label}
						</span>
					</div>
				);
			})}
		</div>
	);
};

/**
 * ProgressChecklist Component
 *
 * Displays an animated checklist with title, icon, and optional subtitle.
 *
 * @param {string} title
 * @param {string} [subtitle]
 * @param {Array<{id: number|string, label: string, delay: number}>} tasks
 * @param {Function} [onComplete]
 * @param {boolean} [canComplete=true] - If false, the checklist loops until it becomes true
 * @param {boolean} [showIcon=true]
 */
const ProgressChecklist = ({
	title,
	subtitle,
	tasks = [],
	onComplete,
	canComplete = true,
	showIcon = true,
}) => {
	const config = getWordPressConfig();
	const contentIndent = showIcon ? 'pl-20' : '';

	return (
		<div className="flex flex-col items-center justify-center py-16 px-6">
			<div className="w-full max-w-2xl">
				<div className="flex items-center gap-4 mb-6">
					{showIcon && (
						<img
							src={`${config?.pluginUrl || ''}js/public/onboarding.svg`}
							alt="Flavio"
							className="size-16 shrink-0"
							aria-hidden="true"
						/>
					)}
					<h1 className="heading-h1">{title}</h1>
				</div>

				{subtitle && (
					<div
						className={`paragraph-regular text-foreground mb-12 [&_strong]:font-semibold [&_strong]:text-foreground ${contentIndent}`}
					>
						{subtitle}
					</div>
				)}

				<div className={contentIndent}>
					<AnimatedTaskList
						tasks={tasks}
						onComplete={onComplete}
						canComplete={canComplete}
					/>
				</div>
			</div>
		</div>
	);
};

export { ProgressChecklist, AnimatedTaskList };
