import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router'
import { MOCK_SPEED_CHALLENGES } from '@/lib/mockData'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card } from '@/components/ui/card'
import { ArrowLeft, Timer, Play, RotateCcw, Check, X } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Watermark } from '@/features/flashcards/components/Watermark'
import { motion, AnimatePresence } from 'framer-motion'
// import confetti from 'canvas-confetti'

export const SpeedChallengePage = () => {
    const navigate = useNavigate()
    const [gameIndex, setGameIndex] = useState(0)
    const [gameState, setGameState] = useState<'idle' | 'running' | 'finished'>('idle')
    const [timeLeft, setTimeLeft] = useState(0)
    const [inputValue, setInputValue] = useState('')
    const [correctAnswers, setCorrectAnswers] = useState<string[]>([])

    // Using ref for fast access in interval without dependency loop
    const timeLeftRef = useRef(0)

    const game = MOCK_SPEED_CHALLENGES[gameIndex % MOCK_SPEED_CHALLENGES.length]

    useEffect(() => {
        let interval: NodeJS.Timeout
        if (gameState === 'running') {
            interval = setInterval(() => {
                const newTime = timeLeftRef.current - 0.1
                timeLeftRef.current = newTime
                setTimeLeft(newTime)

                if (newTime <= 0) {
                    setGameState('finished')
                    timeLeftRef.current = 0
                    setTimeLeft(0)
                    // if (correctAnswers.length > 0) confetti()
                }
            }, 100)
        }
        return () => clearInterval(interval)
    }, [gameState])

    const startGame = () => {
        setCorrectAnswers([])
        setInputValue('')
        setTimeLeft(game.duration)
        timeLeftRef.current = game.duration
        setGameState('running')
    }

    const checkInput = (val: string) => {
        setInputValue(val)
        const word = val.trim().toLowerCase()
        if (game.validAnswers.includes(word) && !correctAnswers.includes(word)) {
            setCorrectAnswers(prev => [word, ...prev])
            setInputValue('') // Clear input on success
        }
    }

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            setInputValue('') // Verify on enter too just in case
        }
    }

    const progress = (timeLeft / game.duration) * 100

    return (
        <div className="h-[calc(100vh-4rem)] relative overflow-hidden p-6 flex flex-col items-center">
            <Watermark text="SPEED RUN" size="lg" className="opacity-5" />

            <div className="w-full max-w-4xl flex items-center justify-between mb-8 z-10">
                <Button variant="ghost" onClick={() => navigate('/mini-games')}>
                    <ArrowLeft className="w-4 h-4 mr-2" /> Back
                </Button>
            </div>

            <div className="flex-1 flex flex-col items-center justify-center w-full max-w-2xl z-10 gap-8">
                <Card className="p-8 w-full bg-card/80 backdrop-blur border-2 shadow-2xl relative overflow-hidden">
                    {/* Timer Bar */}
                    <div className="absolute top-0 left-0 h-2 bg-muted w-full">
                        <motion.div
                            className="h-full bg-gradient-to-r from-green-500 to-emerald-400"
                            animate={{ width: `${progress}%` }}
                            transition={{ duration: 0.1, ease: 'linear' }}
                        />
                    </div>

                    <div className="text-center pt-8 pb-8">
                        {gameState === 'idle' ? (
                            <div className="space-y-6">
                                <Timer className="w-16 h-16 mx-auto text-primary animate-pulse" />
                                <h2 className="text-4xl font-bold">{game.title}</h2>
                                <p className="text-xl text-muted-foreground">{game.prompt}</p>
                                <Button size="lg" onClick={startGame} className="text-xl px-12 py-6 rounded-full shadow-lg shadow-primary/20">
                                    <Play className="w-6 h-6 mr-2" /> Start Challenge
                                </Button>
                            </div>
                        ) : (
                            <div className="space-y-8">
                                <div className="flex justify-between items-center text-4xl font-mono font-bold tabular-nums">
                                    <span className={cn(timeLeft < 3 ? "text-red-500" : "text-foreground")}>
                                        {timeLeft.toFixed(1)}s
                                    </span>
                                    <span className="text-green-600">
                                        {correctAnswers.length} <span className="text-sm font-sans text-muted-foreground uppercase">Words</span>
                                    </span>
                                </div>

                                <h3 className="text-2xl font-bold">{game.prompt}</h3>

                                <div className="relative">
                                    <Input
                                        value={inputValue}
                                        onChange={e => checkInput(e.target.value)}
                                        onKeyDown={handleKeyDown}
                                        disabled={gameState === 'finished'}
                                        placeholder="Type word..."
                                        className="text-center text-2xl h-16 font-bold shadow-inner"
                                        autoFocus
                                    />
                                    {inputValue && (
                                        <X
                                            className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground cursor-pointer hover:text-destructive"
                                            onClick={() => setInputValue('')}
                                        />
                                    )}
                                </div>

                                {/* Answers List */}
                                <div className="flex flex-wrap gap-2 justify-center min-h-[100px]">
                                    <AnimatePresence>
                                        {correctAnswers.map((word) => (
                                            <motion.div
                                                key={word}
                                                initial={{ scale: 0, opacity: 0 }}
                                                animate={{ scale: 1, opacity: 1 }}
                                                className="px-4 py-2 bg-green-100 text-green-700 rounded-full font-bold shadow-sm border border-green-200 flex items-center gap-2"
                                            >
                                                <Check className="w-4 h-4" /> {word}
                                            </motion.div>
                                        ))}
                                    </AnimatePresence>
                                </div>

                                {gameState === 'finished' && (
                                    <div className="animate-in grid place-items-center">
                                        <Button onClick={() => {
                                            setGameIndex(prev => prev + 1)
                                            setGameState('idle')
                                        }} className="gap-2">
                                            <RotateCcw className="w-4 h-4" /> Next Level
                                        </Button>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                </Card>
            </div>
        </div>
    )
}
