import { useState, useRef, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router'
import { useFlashcardSet } from '@/features/flashcards/api/queries'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent } from '@/components/ui/card'
import { Play, Pause, Check, SkipForward, AlertCircle, Volume2, Loader2, ArrowLeft } from 'lucide-react'
import { cn } from '@/lib/utils'
import { speak } from '@/lib/tts'
import { Watermark } from '../components/Watermark'
import { ProgressBar } from '../components/ProgressBar'
import { EndCard } from '../components/EndCard'

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

    const [currentIndex, setCurrentIndex] = useState(0)
    const [userInput, setUserInput] = useState('')
    const [isPlaying, setIsPlaying] = useState(false)
    const [result, setResult] = useState<'correct' | 'incorrect' | null>(null)
    const [score, setScore] = useState(0)
    const [streak, setStreak] = useState(0)
    const [completed, setCompleted] = useState(false)

    // Derived state
    const card = set?.cards?.[currentIndex]

    // Play audio when card changes or when explicitly requested
    useEffect(() => {
        if (card && !completed) {
            playAudio()
        }
    }, [currentIndex, card, completed])

    const playAudio = () => {
        if (!card) return
        setIsPlaying(true)
        speak(card.front, 'no-NO', 0.9)
        // Reset playing state after a rough estimate or just immediately since speak is fire-and-forget mostly
        // A better way would be using onend callback if we promisified it, but for now:
        setTimeout(() => setIsPlaying(false), 2000)
    }

    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>
        )
    }

    if (!card) return <div>Card not found</div>

    const checkAnswer = () => {
        const normalize = (s: string) => s.toLowerCase().trim().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "")
        const isCorrect = normalize(userInput) === normalize(card.front)

        setResult(isCorrect ? 'correct' : 'incorrect')

        if (isCorrect) {
            setScore(score + 1)
            setStreak(streak + 1)
        } else {
            setStreak(0)
        }
    }

    const nextCard = () => {
        if (currentIndex < (set.cards?.length || 0) - 1) {
            setCurrentIndex(currentIndex + 1)
            setUserInput('')
            setResult(null)
        } else {
            setCompleted(true)
        }
    }

    const reset = () => {
        setCurrentIndex(0)
        setScore(0)
        setStreak(0)
        setCompleted(false)
        setResult(null)
        setUserInput('')
    }

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

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

            <div className="w-full relative z-10 mt-8">
                <Button
                    variant="ghost"
                    className="absolute top-0 left-0 -mt-12 md:-ml-12 text-muted-foreground hover:text-foreground"
                    onClick={() => navigate(`/flashcards/${setId}`)}
                >
                    <ArrowLeft className="w-4 h-4 mr-2" /> Exit
                </Button>

                <Card className="w-full border-2 shadow-xl bg-card/90 backdrop-blur-sm">
                    <CardContent className="p-8 flex flex-col items-center gap-8">
                        <div className="text-center">
                            <h2 className="text-sm font-bold text-muted-foreground uppercase tracking-widest mb-2">Listen & Type</h2>
                            <p className="text-xs text-muted-foreground">Type the Norwegian word or phrase you hear.</p>
                        </div>

                        <div className="w-32 h-32 rounded-full bg-primary/10 flex items-center justify-center relative group cursor-pointer" onClick={playAudio}>
                            <div className={cn("absolute inset-0 rounded-full border-4 border-primary/30 scale-100 transition-transform duration-1000", isPlaying && "animate-ping")} />
                            <Button
                                variant="outline"
                                size="icon"
                                className="w-24 h-24 rounded-full border-4 border-primary text-primary hover:bg-primary hover:text-white transition-all scale-100 group-hover:scale-105 active:scale-95 z-10"
                            >
                                <Volume2 className={cn("w-10 h-10", isPlaying && "animate-pulse")} />
                            </Button>
                        </div>

                        <div className="w-full space-y-4 max-w-md">
                            <Input
                                value={userInput}
                                onChange={(e) => setUserInput(e.target.value)}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter' && !result) checkAnswer()
                                    else if (e.key === 'Enter' && result === 'correct') nextCard()
                                }}
                                placeholder="Type here..."
                                className="text-xl p-6 h-auto text-center shadow-inner"
                                disabled={result === 'correct'}
                                autoFocus
                            />

                            <div className="flex justify-center gap-4 min-h-[50px]">
                                {result === null && (
                                    <Button onClick={checkAnswer} size="lg" className="w-full font-bold">
                                        Check Answer
                                    </Button>
                                )}

                                {result === 'incorrect' && (
                                    <Button onClick={checkAnswer} variant="destructive" size="lg" className="w-full font-bold">
                                        Try Again
                                    </Button>
                                )}

                                {result === 'correct' && (
                                    <Button onClick={nextCard} variant="default" size="lg" className="w-full bg-green-600 hover:bg-green-700 font-bold">
                                        Next <SkipForward className="ml-2 w-4 h-4" />
                                    </Button>
                                )}
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {result === 'incorrect' && (
                    <div className="mt-6 flex items-center justify-center gap-2 text-red-500 animate-in slide-in-from-top-2 bg-red-100/50 dark:bg-red-900/20 p-2 rounded-lg">
                        <AlertCircle className="w-5 h-5" />
                        <span className="font-medium">Incorrect. Listen closely and try again!</span>
                    </div>
                )}

                {result === 'correct' && (
                    <div className="mt-6 flex flex-col items-center gap-2 text-green-600 animate-in slide-in-from-top-2 bg-green-100/50 dark:bg-green-900/20 p-4 rounded-lg">
                        <div className="flex items-center gap-2 font-bold text-xl">
                            <Check className="w-6 h-6" />
                            <span>Correct!</span>
                        </div>
                        <div className="text-center">
                            <p className="text-foreground font-medium text-lg">{card.front}</p>
                            <p className="text-muted-foreground">{card.back}</p>
                        </div>
                    </div>
                )}
            </div>
        </div>
    )
}
