import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router'
import { MOCK_STOP_THE_BUS_CATEGORIES } from '@/lib/mockData'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card } from '@/components/ui/card'
import { ArrowLeft, Timer, RotateCcw, CheckCircle2, XCircle, Trophy } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Watermark } from '@/features/flashcards/components/Watermark'
// import { motion } from 'framer-motion'

const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ'.split('')
const GAME_DURATION = 120 // 2 minutes

export const StopTheBusPage = () => {
    const navigate = useNavigate()
    const [status, setStatus] = useState<'setup' | 'playing' | 'finished'>('setup')
    const [selectedLetter, setSelectedLetter] = useState('')
    const [activeCategories, setActiveCategories] = useState<string[]>([])
    const [timeLeft, setTimeLeft] = useState(GAME_DURATION)
    const [inputs, setInputs] = useState<Record<string, string[]>>({})
    const [scores, setScores] = useState<Record<string, boolean[]>>({})

    // Using ref for timer to avoid re-render lag issues if we went sub-second
    const intervalRef = useRef<NodeJS.Timeout | null>(null)

    useEffect(() => {
        if (status === 'playing') {
            intervalRef.current = setInterval(() => {
                setTimeLeft((prev) => {
                    if (prev <= 1) {
                        finishGame()
                        return 0
                    }
                    return prev - 1
                })
            }, 1000)
        }
        return () => {
            if (intervalRef.current) clearInterval(intervalRef.current)
        }
    }, [status])

    const finishGame = () => {
        if (intervalRef.current) clearInterval(intervalRef.current)
        setStatus('finished')
        calculateScore()
    }

    const startGame = (letter: string) => {
        setSelectedLetter(letter)
        // Pick 3 unique random categories
        const shuffled = [...MOCK_STOP_THE_BUS_CATEGORIES].sort(() => 0.5 - Math.random())
        const selected = shuffled.slice(0, 3)
        setActiveCategories(selected)

        // Initialize inputs
        const initialInputs: Record<string, string[]> = {}
        selected.forEach(cat => {
            initialInputs[cat] = Array(5).fill('')
        })
        setInputs(initialInputs)

        setTimeLeft(GAME_DURATION)
        setStatus('playing')
    }

    const handleInputChange = (category: string, index: number, value: string) => {
        setInputs(prev => ({
            ...prev,
            [category]: prev[category].map((val, i) => i === index ? value : val)
        }))
    }

    const calculateScore = () => {
        const newScores: Record<string, boolean[]> = {}

        activeCategories.forEach(cat => {
            newScores[cat] = inputs[cat].map(word => {
                const w = word.trim().toUpperCase()
                // Mock AI Validation: Must start with letter and be > 2 chars
                return w.length > 2 && w.startsWith(selectedLetter)
            })
        })
        setScores(newScores)
    }

    const getTotalScore = () => {
        let total = 0
        Object.values(scores).forEach(catScores => {
            total += catScores.filter(Boolean).length * 10
        })
        return total
    }

    const formatTime = (seconds: number) => {
        const m = Math.floor(seconds / 60)
        const s = seconds % 60
        return `${m}:${s.toString().padStart(2, '0')}`
    }

    return (
        <div className="min-h-[calc(100vh-4rem)] relative bg-background p-6 flex flex-col items-center overflow-x-hidden">
            <Watermark text={selectedLetter || "ABC"} size="lg" className="opacity-[0.03]" />

            <div className="w-full max-w-6xl 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>
                {status === 'playing' && (
                    <div className={cn("text-4xl font-mono font-bold tabular-nums flex items-center gap-2", timeLeft < 10 ? "text-red-500 animate-pulse" : "text-primary")}>
                        <Timer className="w-8 h-8" />
                        {formatTime(timeLeft)}
                    </div>
                )}
            </div>

            <div className="w-full max-w-5xl z-10 flex-1 flex flex-col">
                {status === 'setup' && (
                    <div className="flex-1 flex flex-col items-center justify-center animate-in zoom-in-95 duration-500">
                        <h1 className="text-4xl md:text-5xl font-bold mb-4 bg-gradient-to-r from-blue-600 to-cyan-500 bg-clip-text text-transparent">
                            Stop the Bus
                        </h1>
                        <p className="text-xl text-muted-foreground mb-12">Pick a starting letter for this round</p>

                        <div className="flex flex-wrap justify-center gap-3 max-w-3xl">
                            {ALPHABET.map((letter) => (
                                <button
                                    key={letter}
                                    onClick={() => startGame(letter)}
                                    className="w-12 h-12 md:w-16 md:h-16 rounded-xl border-2 border-border bg-card hover:bg-primary hover:text-primary-foreground hover:border-primary hover:scale-110 transition-all text-xl md:text-2xl font-bold shadow-sm"
                                >
                                    {letter}
                                </button>
                            ))}
                        </div>
                    </div>
                )}

                {status !== 'setup' && (
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6 animate-in slide-in-from-bottom-8 duration-500">
                        {activeCategories.map((category) => (
                            <Card key={category} className="flex flex-col overflow-hidden border-t-4 border-t-primary shadow-lg bg-card/80 backdrop-blur-sm">
                                <div className="p-4 bg-muted/30 border-b font-bold text-center text-lg">
                                    {category}
                                </div>
                                <div className="p-4 space-y-3 flex-1">
                                    {inputs[category].map((val, idx) => (
                                        <div key={idx} className="relative">
                                            <Input
                                                value={val}
                                                onChange={(e) => handleInputChange(category, idx, e.target.value)}
                                                disabled={status === 'finished'}
                                                className={cn(
                                                    "h-10 text-lg transition-colors",
                                                    status === 'finished' && scores[category]?.[idx] && "bg-green-500/10 border-green-500/50 text-green-700 font-medium",
                                                    status === 'finished' && !scores[category]?.[idx] && val && "bg-red-500/10 border-red-500/50 text-red-700 line-through opacity-70"
                                                )}
                                                placeholder={`${selectedLetter}...`}
                                            />
                                            {status === 'finished' && val && (
                                                <div className="absolute right-3 top-1/2 -translate-y-1/2">
                                                    {scores[category]?.[idx] ? (
                                                        <CheckCircle2 className="w-5 h-5 text-green-600" />
                                                    ) : (
                                                        <XCircle className="w-5 h-5 text-red-500" />
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </Card>
                        ))}
                    </div>
                )}

                {status === 'playing' && (
                    <div className="mt-8 flex justify-center">
                        <Button
                            size="lg"
                            className="bg-destructive hover:bg-destructive/90 text-destructive-foreground text-xl px-12 py-8 rounded-full shadow-xl hover:scale-105 transition-transform"
                            onClick={finishGame}
                        >
                            STOP THE BUS!
                        </Button>
                    </div>
                )}

                {status === 'finished' && (
                    <div className="mt-8 flex flex-col items-center animate-in fade-in zoom-in slide-in-from-bottom-4 duration-700">
                        <div className="bg-card border p-8 rounded-2xl shadow-2xl flex flex-col items-center gap-4 mb-8">
                            <Trophy className="w-16 h-16 text-yellow-500" />
                            <div className="text-center">
                                <h3 className="text-lg text-muted-foreground uppercase font-bold tracking-widest">Total Score</h3>
                                <div className="text-6xl font-black text-foreground">{getTotalScore()}</div>
                            </div>
                        </div>
                        <Button onClick={() => setStatus('setup')} size="lg" className="text-lg h-12 px-8">
                            <RotateCcw className="w-5 h-5 mr-2" /> Play Again
                        </Button>
                    </div>
                )}
            </div>
        </div>
    )
}
