'use client';

import { useState, useEffect } from 'react';
import { questions } from '../questions';
import Question from './question';
import { WinScreen } from './win-screen';

const defaults = {
	spread: 360,
	ticks: 100,
	gravity: 10,
	decay: 0.7,
	startVelocity: 30,
	shapes: ['heart'],
	colors: ['FFC0CB', 'FF69B4', 'FF1493', 'C71585'],
};

export default function Quiz() {
	const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
	const [selectedAnswerIndex, setSelectedAnswerIndex] = useState<number | null>(null);
	const [isCorrect, setIsCorrect] = useState<boolean | null>(null);
	const [isCompleted, setIsCompleted] = useState(false);

	const currentQuestion = questions[currentQuestionIndex];

	useEffect(() => {
		let timer: NodeJS.Timeout;
		if (isCorrect === false) {
			timer = setTimeout(() => {
				setIsCorrect(null);
				setSelectedAnswerIndex(null);
			}, 1500); // 1500ms = 3 flashes of 500ms each
		}
		return () => clearTimeout(timer);
	}, [isCorrect]);

	const handleAnswerClick = (index: number, event: React.MouseEvent) => {
		setSelectedAnswerIndex(index);
		const correct = index === currentQuestion.correctAnswerIndex;
		setIsCorrect(correct);

		if (correct) {
			const x = event.clientX / window.innerWidth;
			const y = event.clientY / window.innerHeight;

			// @ts-ignore
			confetti({
				...defaults,
				origin: { x, y },
				particleCount: 50,
				scalar: 2,
			});

			// @ts-ignore
			confetti({
				...defaults,
				origin: { x, y },
				particleCount: 25,
				scalar: 3,
			});

			// @ts-ignore
			confetti({
				...defaults,
				origin: { x, y },
				particleCount: 10,
				scalar: 4,
			});

			setTimeout(() => {
				if (currentQuestionIndex === questions.length - 1) {
					setIsCompleted(true);
				} else {
					setCurrentQuestionIndex(prev => prev + 1);
				}
				setSelectedAnswerIndex(null);
				setIsCorrect(null);
			}, 1000);
		}
	};

	return (
		<div className="container mx-auto p-4 max-w-2xl min-h-screen flex items-center justify-center">
			{isCompleted ? (
				<WinScreen />
			) : (
				<Question
					question={currentQuestion.question}
					image={currentQuestion.image}
					answers={currentQuestion.answers}
					selectedAnswerIndex={selectedAnswerIndex}
					isCorrect={isCorrect}
					onAnswerClick={handleAnswerClick}
				/>
			)}
		</div>
	);
}
