import { useState, useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router'
import { MOCK_HANGMAN_GAMES } from '@/lib/mockData'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { ArrowLeft, RotateCcw, Heart, HelpCircle } 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 MAX_LIVES = 6

export const HangmanPage = () => {
    const navigate = useNavigate()
    const [gameIndex, setGameIndex] = useState(0)
    const [guessedLetters, setGuessedLetters] = useState<string[]>([])
    const [lives, setLives] = useState(MAX_LIVES)
    const [status, setStatus] = useState<'playing' | 'won' | 'lost'>('playing')

    const game = MOCK_HANGMAN_GAMES[gameIndex % MOCK_HANGMAN_GAMES.length]

    const wordLetters = useMemo(() => game.word.toUpperCase().split(''), [game])

    useEffect(() => {
        // Check win/loss
        const isWon = wordLetters.every(l => guessedLetters.includes(l))
        const isLost = lives <= 0

        if (isWon) setStatus('won')
        else if (isLost) setStatus('lost')
    }, [guessedLetters, lives, wordLetters])

    const handleGuess = (letter: string) => {
        if (status !== 'playing' || guessedLetters.includes(letter)) return

        setGuessedLetters(prev => [...prev, letter])
        if (!wordLetters.includes(letter)) {
            setLives(prev => prev - 1)
        }
    }

    const handleRestart = () => {
        if (status === 'won') {
            setGameIndex(prev => prev + 1)
        }
        setGuessedLetters([])
        setLives(MAX_LIVES)
        setStatus('playing')
    }

    return (
        <div className="h-[calc(100vh-4rem)] relative overflow-hidden p-6 flex flex-col items-center">
            <Watermark text="HANGMAN" 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 className="flex gap-1">
                    {Array.from({ length: MAX_LIVES }).map((_, i) => (
                        <Heart
                            key={i}
                            className={cn(
                                "w-6 h-6 transition-colors duration-500",
                                i < lives ? "fill-red-500 text-red-500" : "fill-transparent text-muted-foreground/30"
                            )}
                        />
                    ))}
                </div>
            </div>

            <div className="flex-1 flex flex-col items-center justify-center w-full max-w-2xl z-10 gap-12">
                <Card className="p-8 w-full bg-card/80 backdrop-blur border-2 shadow-2xl animate-in zoom-in-95 duration-500">
                    <div className="text-center mb-12">
                        <div className="flex items-center justify-center gap-2 text-muted-foreground text-sm uppercase tracking-widest font-bold mb-4">
                            <HelpCircle className="w-4 h-4" /> Hint
                        </div>
                        <p className="text-xl md:text-2xl font-serif text-foreground/90 italic">
                            "{game.hint}"
                        </p>
                    </div>

                    <div className="flex flex-wrap justify-center gap-3 mb-12 min-h-[4rem]">
                        {wordLetters.map((letter, idx) => {
                            const isGuessed = guessedLetters.includes(letter)
                            const isLost = status === 'lost'
                            return (
                                <motion.div
                                    key={idx}
                                    initial={{ scale: 0.8, opacity: 0 }}
                                    animate={{ scale: 1, opacity: 1 }}
                                    className={cn(
                                        "w-10 h-14 md:w-14 md:h-20 border-b-4 flex items-center justify-center text-3xl md:text-4xl font-mono font-bold transition-colors",
                                        isGuessed
                                            ? "border-primary text-primary"
                                            : isLost
                                                ? "border-destructive text-destructive"
                                                : "border-muted-foreground/30 text-transparent"
                                    )}
                                >
                                    {isGuessed || isLost ? letter : ''}
                                </motion.div>
                            )
                        })}
                    </div>

                    {status !== 'playing' ? (
                        <div className="text-center animate-in slide-in-from-bottom-4">
                            <h3 className={cn("text-3xl font-bold mb-4", status === 'won' ? "text-green-500" : "text-destructive")}>
                                {status === 'won' ? "Correct!" : "Game Over"}
                            </h3>
                            <Button onClick={handleRestart} size="lg" className="gap-2">
                                <RotateCcw className="w-4 h-4" />
                                {status === 'won' ? "Next Word" : "Try Again"}
                            </Button>
                        </div>
                    ) : (
                        <div className="flex flex-wrap justify-center gap-2">
                            {ALPHABET.map((letter) => {
                                const isGuessed = guessedLetters.includes(letter)
                                const isCorrect = wordLetters.includes(letter)
                                return (
                                    <button
                                        key={letter}
                                        onClick={() => handleGuess(letter)}
                                        disabled={isGuessed}
                                        className={cn(
                                            "w-10 h-10 rounded-lg text-sm font-bold transition-all duration-200 shadow-sm border",
                                            isGuessed
                                                ? isCorrect
                                                    ? "bg-green-100 border-green-300 text-green-700 opacity-50"
                                                    : "bg-red-100 border-red-300 text-red-700 opacity-50"
                                                : "bg-card border-border hover:bg-primary hover:text-primary-foreground hover:scale-110 hover:shadow-md"
                                        )}
                                    >
                                        {letter}
                                    </button>
                                )
                            })}
                        </div>
                    )}
                </Card>
            </div>
        </div>
    )
}
