import { useState } from 'react'
import { useParams, useNavigate } from 'react-router'
import { useFlashcardSet } from '@/features/flashcards/api/queries'
import { Loader2 } from 'lucide-react'
import { FlipCard } from '../components/FlipCard'
import { Button } from '@/components/ui/button'
import { Check, X, ArrowLeft, RotateCw } 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'

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

    const [currentIndex, setCurrentIndex] = useState(0)
    const [completed, setCompleted] = useState(false)
    const [score, setScore] = useState(0)
    const [streak, setStreak] = useState(0)

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

    const handleResult = (correct: boolean) => {
        if (correct) {
            setScore(score + 1)
            setStreak(streak + 1)
        } else {
            setStreak(0)
        }

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

    const reset = () => {
        setCurrentIndex(0)
        setScore(0)
        setStreak(0)
        setCompleted(false)
    }

    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-8 max-w-4xl mx-auto overflow-hidden relative">
            <ProgressBar current={currentIndex} total={set.cards.length} streak={streak} />
            <Watermark text="cards" size="lg" />

            <div className="w-full relative z-10 pt-16">
                <AnimatePresence mode="wait">
                    <motion.div
                        key={currentIndex}
                        initial={{ opacity: 0, x: 100 }}
                        animate={{ opacity: 1, x: 0 }}
                        exit={{ opacity: 0, x: -100 }}
                        transition={{ type: "spring", stiffness: 200, damping: 25 }}
                        className="w-full flex justify-center"
                    >
                        <FlipCard
                            key={`${setId}-${currentIndex}`}
                            card={set.cards[currentIndex]}
                            onResult={handleResult}
                        />
                    </motion.div>
                </AnimatePresence>
            </div>
        </div>
    )
}
