import { useParams, useNavigate } from 'react-router'
import { useState, useRef, useMemo, useEffect } from 'react'
import { VocabSidebar } from '../components/VocabSidebar'
import { ClozeInput } from '../components/ClozeInput'
import { Button } from '@/components/ui/button'
import { ArrowLeft, CheckCircle, Loader2 } from 'lucide-react'
import { Card } from '@/components/ui/card'
import { Watermark } from '@/features/flashcards/components/Watermark'
import { getStoryById, GeneratedStory } from '@/lib/db'

export const StoryReaderPage = () => {
    const { storyId } = useParams()
    const navigate = useNavigate()
    const [story, setStory] = useState<GeneratedStory | null>(null)
    const [isLoading, setIsLoading] = useState(true)
    const [solvedWords, setSolvedWords] = useState<string[]>([])

    // Store refs to inputs for tabbing
    const inputRefs = useRef<(HTMLInputElement | null)[]>([])

    useEffect(() => {
        const loadStory = async () => {
            if (!storyId) return
            try {
                const data = await getStoryById(storyId)
                setStory(data)
            } catch (e) {
                console.error("Failed to load story", e)
            } finally {
                setIsLoading(false)
            }
        }
        loadStory()
    }, [storyId])

    // Parse content to identify text parts and gaps
    // "Idag er det {{sol}} i Oslo." -> ["Idag er det ", "{{sol}}", " i Oslo."]
    const parts = useMemo(() => {
        if (!story) return []
        return story.content.split(/(\{\{.*?\}\})/g)
    }, [story?.content])

    const gapMatches = useMemo(() => {
        if (!story) return []
        return story.content.match(/\{\{.*?\}\}/g) || []
    }, [story?.content])

    const shuffledVocab = useMemo(() => {
        if (!story?.vocab) return []
        const vocab = [...story.vocab]
        for (let i = vocab.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [vocab[i], vocab[j]] = [vocab[j], vocab[i]];
        }
        return vocab;
    }, [story?.vocab])

    const handleSolve = (word: string) => {
        if (!solvedWords.includes(word.toLowerCase())) {
            setSolvedWords(prev => [...prev, word.toLowerCase()])
        }
    }

    const focusNext = (currentIndex: number) => {
        const nextInput = inputRefs.current[currentIndex + 1]
        if (nextInput) {
            nextInput.focus()
        }
    }

    if (isLoading) {
        return <div className="flex h-screen items-center justify-center"><Loader2 className="w-8 h-8 animate-spin text-muted-foreground" /></div>
    }

    if (!story) return <div className="flex h-screen items-center justify-center text-muted-foreground">Story not found</div>

    // Counter for assigning refs
    let gapIndex = 0

    return (
        <div className="flex h-[calc(100vh-4rem)] relative overflow-hidden">
            <Watermark text="start reading" size="lg" className="opacity-5" />

            {/* Sidebar */}
            <aside className="w-80 hidden md:block h-full overflow-hidden shrink-0 z-10 bg-card/80 backdrop-blur border-r">
                <VocabSidebar vocab={shuffledVocab} solvedWords={solvedWords} />
            </aside>

            {/* Main Area */}
            <main className="flex-1 p-8 overflow-y-auto z-10 relative">
                <div className="max-w-3xl mx-auto">
                    <Button variant="ghost" className="mb-6 -ml-4 hover:bg-transparent hover:text-primary" onClick={() => navigate('/smart-reading')}>
                        <ArrowLeft className="w-4 h-4 mr-2" /> Back to Stories
                    </Button>

                    <Card className="p-10 md:p-16 shadow-2xl border-2 border-primary/10 bg-card/90 backdrop-blur-md rounded-xl min-h-[60vh] relative transition-all">
                        <div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-primary/20 via-primary/60 to-primary/20" />

                        <h1 className="text-4xl font-serif font-bold mb-12 text-center text-primary/80">{story.title}</h1>

                        <div className="font-serif text-xl md:text-2xl leading-[2.5] text-justify text-foreground/90">
                            {parts.map((part, idx) => {
                                if (part.startsWith('{{') && part.endsWith('}}')) {
                                    const answer = part.slice(2, -2)
                                    const currentRefIndex = gapIndex++
                                    return (
                                        <ClozeInput
                                            key={idx}
                                            answer={answer}
                                            onSolve={handleSolve}
                                            inputRef={el => (inputRefs.current[currentRefIndex] = el)}
                                            onTab={() => focusNext(currentRefIndex)}
                                        />
                                    )
                                }
                                return <span key={idx}>{part}</span>
                            })}
                        </div>

                        {solvedWords.length === gapMatches.length && (
                            <div className="mt-16 p-8 bg-green-500/10 border-2 border-green-500/20 rounded-2xl flex items-center gap-6 animate-in zoom-in slide-in-from-bottom-8 duration-500 shadow-xl">
                                <div className="p-4 bg-green-500 rounded-full text-white shadow-lg shadow-green-500/40">
                                    <CheckCircle className="w-8 h-8" />
                                </div>
                                <div>
                                    <h3 className="text-2xl font-bold text-green-700 dark:text-green-400 mb-1">Story Completed!</h3>
                                    <p className="text-green-800 dark:text-green-300 font-medium">Splendid! You've mastered all the vocabulary in this text.</p>
                                </div>
                            </div>
                        )}
                    </Card>
                </div>
            </main>
        </div>
    )
}
