import { useState, useRef, useEffect, useMemo } from 'react'
import { useParams, useNavigate } from 'react-router'
import { useFlashcardSet } from '@/features/flashcards/api/queries'
import { Button } from '@/components/ui/button'
import { HelpCircle, ArrowRight, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { motion, AnimatePresence } from 'framer-motion'
import { Watermark } from '../components/Watermark'
import { ProgressBar } from '../components/ProgressBar'
import { EndCard } from '../components/EndCard'

// Helper to tokenize sentence into [word, punctuation, word, ...]
const tokenize = (text: string) => {
    return text.split(/([^\w\u00C0-\u017F]+)/).filter(t => t.length > 0)
}

const isWord = (token: string) => {
    return /^[\w\u00C0-\u017F]+$/.test(token)
}

interface WordInputProps {
    expected: string
    value: string
    status: 'idle' | 'correct' | 'incorrect'
    onChange: (val: string) => void
    onComplete: () => void
    onBackspaceFromEmpty: () => void
    inputRef: (el: HTMLInputElement | null) => void
    isFocused: boolean
}

const WordInput = ({ expected, value, status, onChange, onComplete, onBackspaceFromEmpty, inputRef, isFocused }: WordInputProps) => {
    const displayChars = useMemo(() => {
        const chars = []
        for (let i = 0; i < expected.length; i++) {
            chars.push(value[i] || '_')
        }
        return chars
    }, [expected, value])

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // Strip spaces to prevent them from "eating" the underscores
        const rawVal = e.target.value.replace(/\s/g, '')
        const newVal = rawVal.slice(0, expected.length)
        onChange(newVal)
        if (newVal.length === expected.length) {
            onComplete()
        }
    }

    return (
        <div className="relative inline-flex justify-center mx-1 my-2">
            <div
                className={cn(
                    "flex justify-center w-full font-mono text-xl md:text-2xl font-bold pointer-events-none select-none transition-all duration-200",
                    "bg-card border-none shadow-[0_3px_0_hsl(var(--background)),0_3px_8px_rgba(0,0,0,0.1)] rounded px-2 py-1",
                    status === 'correct' && "shadow-[0_3px_0_hsl(var(--success)),0_3px_8px_rgba(0,0,0,0.1)] text-green-600",
                    status === 'incorrect' && "shadow-[0_3px_0_hsl(var(--destructive)),0_3px_8px_rgba(0,0,0,0.1)] text-red-500",
                    isFocused && status === 'idle' && "shadow-[0_3px_0_hsl(var(--primary)),0_3px_8px_rgba(0,0,0,0.1)] -translate-y-[3px]"
                )}
            >
                {/*  Render spaced characters */}
                <span className="tracking-[0.5em] mr-[-0.5em]">{displayChars.join('')}</span>
            </div>

            <input
                ref={inputRef}
                value={value}
                onChange={handleChange}
                onKeyDown={(e) => {
                    // Navigate on Space
                    if (e.key === ' ') {
                        e.preventDefault()
                        onComplete()
                    }
                    if (e.key === 'Backspace' && value.length === 0) onBackspaceFromEmpty()
                }}
                className="absolute inset-0 w-full h-full opacity-0 cursor-text"
                autoComplete="off"
                disabled={status !== 'idle'}
            />
        </div>
    )
}

export const SpellingModePage = () => {
    const { setId } = useParams()
    const navigate = useNavigate()
    const { data: set, isLoading } = useFlashcardSet(setId || '')

    const [currentIndex, setCurrentIndex] = useState(0)
    const [status, setStatus] = useState<'idle' | 'correct' | 'incorrect'>('idle')
    const [score, setScore] = useState(0)
    const [streak, setStreak] = useState(0)
    const [completed, setCompleted] = useState(false)
    const [showAnswer, setShowAnswer] = useState(false)
    const [focusedIndex, setFocusedIndex] = useState<number>(0)

    const [inputValues, setInputValues] = useState<string[]>([])
    const inputRefs = useRef<(HTMLInputElement | null)[]>([])

    if (isLoading) return <div className="flex justify-center items-center h-screen"><Loader2 className="w-8 h-8 animate-spin" /></div>
    if (!set) return <div>Set not found</div>

    if (!set.cards || set.cards.length === 0) {
        return (
            <div className="flex flex-col items-center justify-center min-h-[calc(100vh-4rem)] p-8 text-center">
                <h2 className="text-2xl font-bold mb-4">No Cards Found</h2>
                <p className="text-muted-foreground mb-6">There are no cards in this set. Add some to continue!</p>
                <Button onClick={() => navigate(`/flashcards/${setId}/list`)}>
                    Manage Cards
                </Button>
            </div>
        )
    }

    // Ensure card exists before accessing
    const card = set.cards && set.cards[currentIndex] ? set.cards[currentIndex] : null
    if (!card) return <div>Card not found</div>

    const tokens = useMemo(() => tokenize(card.front), [card])

    useEffect(() => {
        setInputValues(tokens.map(t => isWord(t) ? '' : t))
        setStatus('idle')
        setShowAnswer(false)
        setFocusedIndex(0)

        // Find first word
        const firstWordIdx = tokens.findIndex(t => isWord(t))
        if (firstWordIdx !== -1) {
            setFocusedIndex(firstWordIdx)
            setTimeout(() => inputRefs.current[firstWordIdx]?.focus(), 50)
        }

    }, [currentIndex, tokens])

    const handleInputChange = (index: number, val: string) => {
        const newValues = [...inputValues]
        newValues[index] = val
        setInputValues(newValues)
    }

    const focusNext = (currIdx: number) => {
        for (let i = currIdx + 1; i < tokens.length; i++) {
            if (isWord(tokens[i])) {
                inputRefs.current[i]?.focus()
                setFocusedIndex(i)
                return
            }
        }
    }

    const focusPrev = (currIdx: number) => {
        for (let i = currIdx - 1; i >= 0; i--) {
            if (isWord(tokens[i])) {
                inputRefs.current[i]?.focus()
                setFocusedIndex(i)
                return
            }
        }
    }

    const checkAnswer = (e?: React.FormEvent) => {
        e?.preventDefault()
        if (status !== 'idle') return

        const userSentence = inputValues.join('')
        const normalize = (s: string) => s.toLowerCase().trim()

        const isCorrect = normalize(userSentence) === normalize(card.front)

        setStatus(isCorrect ? 'correct' : 'incorrect')
        if (isCorrect) {
            setScore(score + 1)
            setStreak(streak + 1)
        } else {
            setStreak(0)
        }
    }

    const handleGiveUp = () => {
        setStatus('incorrect')
        setShowAnswer(true)
        setStreak(0)
    }

    const nextCard = () => {
        if (currentIndex < set.cards.length - 1) {
            setCurrentIndex(currentIndex + 1)
        } else {
            setCompleted(true)
        }
    }

    const handleRestart = () => {
        setCurrentIndex(0)
        setScore(0)
        setStreak(0)
        setCompleted(false)
        setStatus('idle')
    }

    if (completed) {
        return <EndCard score={score} total={set.cards.length} streak={streak} onRestart={handleRestart} setId={setId || ''} />
    }

    return (
        <div className="flex flex-col items-center justify-center min-h-[calc(100vh-4rem)] p-4 md:p-8 max-w-5xl mx-auto relative overflow-hidden">
            <ProgressBar current={currentIndex} total={set.cards.length} streak={streak} />
            <Watermark text="spelling" size="lg" />

            <div className="w-full max-w-3xl relative z-10 mt-16 md:mt-0">
                <AnimatePresence mode="wait">
                    <motion.div
                        key={currentIndex}
                        initial={{ opacity: 0, x: 50, scale: 0.9 }}
                        animate={{ opacity: 1, x: 0, scale: 1 }}
                        exit={{ opacity: 0, x: -50, scale: 0.9 }}
                        transition={{ type: "spring", stiffness: 200, damping: 25 }}
                        className={cn(
                            "bg-card/80 backdrop-blur-md border-2 rounded-2xl p-8 md:p-12 shadow-2xl text-center flex flex-col items-center gap-8 transition-colors duration-300",
                            status === 'correct' ? "border-green-400" :
                                status === 'incorrect' ? "border-red-400" : "border-primary/20"
                        )}
                    >
                        <div>
                            <p className="text-sm font-bold text-muted-foreground uppercase tracking-widest mb-4">Translate to Norwegian</p>
                            <h2 className="text-3xl md:text-5xl font-bold text-foreground mb-2">{card.back}</h2>
                        </div>

                        <form onSubmit={checkAnswer} className="flex flex-wrap justify-center items-center gap-1 w-full relative min-h-[80px]">
                            {tokens.map((token, idx) => {
                                if (!isWord(token)) {
                                    return <span key={idx} className="text-2xl font-mono mx-1 select-none opacity-50">{token}</span>
                                }
                                return (
                                    <WordInput
                                        key={idx}
                                        expected={token}
                                        value={inputValues[idx] || ''}
                                        status={status}
                                        onChange={(val) => handleInputChange(idx, val)}
                                        onComplete={() => focusNext(idx)}
                                        onBackspaceFromEmpty={() => focusPrev(idx)}
                                        inputRef={(el) => (inputRefs.current[idx] = el)}
                                        isFocused={focusedIndex === idx}
                                    />
                                )
                            })}
                        </form>

                        <div className="min-h-[60px] w-full flex justify-center items-center">
                            {status === 'idle' ? (
                                <div className="flex gap-4 w-full max-w-xs">
                                    <Button size="lg" className="flex-1 font-bold tracking-wide shadow-lg hover:translate-y-[-2px] transition-all" onClick={checkAnswer}>
                                        CHECK
                                    </Button>
                                    <Button variant="outline" size="icon" className="shrink-0" onClick={handleGiveUp} title="Give Up">
                                        <HelpCircle className="w-5 h-5" />
                                    </Button>
                                </div>
                            ) : (
                                <motion.div
                                    initial={{ opacity: 0, y: 10 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    className="w-full max-w-md"
                                >
                                    {(status === 'incorrect' || showAnswer) && (
                                        <div className="bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300 px-4 py-2 rounded-lg font-mono text-lg font-bold mb-4 shadow-inner">
                                            {card.front}
                                        </div>
                                    )}
                                    <Button
                                        size="lg"
                                        className={cn(
                                            "w-full font-bold tracking-wide shadow-lg group",
                                            status === 'correct' ? "bg-green-600 hover:bg-green-700 text-white" : "bg-red-600 hover:bg-red-700 text-white"
                                        )}
                                        onClick={nextCard}
                                        autoFocus
                                    >
                                        CONTINUE <ArrowRight className="w-5 h-5 ml-2 group-hover:translate-x-1 transition-transform" />
                                    </Button>
                                </motion.div>
                            )}
                        </div>

                    </motion.div>
                </AnimatePresence>
            </div>
        </div>
    )
}
