import { useNavigate } from 'react-router'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

import { BookOpen, Coffee, MapPin, Sparkles, Plus, Loader2, Trash2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useState, useEffect } from 'react'
import { getStories, GeneratedStory, deleteStory } from '@/lib/db'
import { SmartReadingService } from '@/services/smartReading'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog'

const GRADIENTS = [
    "from-blue-500 to-cyan-400",
    "from-purple-500 to-pink-400",
    "from-orange-500 to-amber-400",
    "from-emerald-500 to-green-400",
]

const ICONS = [BookOpen, Coffee, MapPin, Sparkles]

export const SmartReadingDashboard = () => {
    const navigate = useNavigate()
    const [stories, setStories] = useState<GeneratedStory[]>([])
    const [isLoading, setIsLoading] = useState(true)
    const [isGenerating, setIsGenerating] = useState(false)
    const [isDialogOpen, setIsDialogOpen] = useState(false)

    // Generation Form
    const [topic, setTopic] = useState('')
    const [difficulty, setDifficulty] = useState<'Easy' | 'Medium' | 'Hard'>('Easy')

    const loadStories = async () => {
        try {
            const data = await getStories()
            setStories(data)
        } catch (e) {
            console.error("Failed to load stories", e)
        } finally {
            setIsLoading(false)
        }
    }

    useEffect(() => {
        loadStories()
    }, [])

    const handleGenerate = async () => {
        if (!topic.trim()) return
        setIsGenerating(true)
        try {
            // Check if backend is ready? Service handles it via chatCompletion
            // Ideally we'd ensure Chat Server is running, similar to Visual Page.
            // But let's assume user has run chat or we catch error.

            await SmartReadingService.generateStory(topic, difficulty)
            await loadStories()
            setIsDialogOpen(false)
            setTopic('')
        } catch (e) {
            console.error("Generation failed", e)
            alert("Failed to generate story. Make sure AI Backend is running (Chat).")
        } finally {
            setIsGenerating(false)
        }
    }

    const handleDelete = async (e: React.MouseEvent, id: string) => {
        e.stopPropagation()
        if (confirm("Are you sure you want to delete this story?")) {
            await deleteStory(id)
            await loadStories()
        }
    }

    return (
        <div className="p-8 max-w-5xl mx-auto min-h-[calc(100vh-4rem)]">
            <div className="mb-8 flex justify-between items-end">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Smart Reading Stories</h1>
                    <p className="text-muted-foreground">Improve your reading comprehension with AI-generated stories.</p>
                </div>

                <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                    <DialogTrigger asChild>
                        <Button className="gap-2">
                            <Plus className="w-4 h-4" /> Generate New Story
                        </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-md">
                        <DialogHeader>
                            <DialogTitle>Generate a New Story</DialogTitle>
                            <DialogDescription>
                                Choose a topic and difficulty level. The AI will create a unique story for you.
                            </DialogDescription>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                            <div className="grid gap-2">
                                <Label htmlFor="topic">Topic</Label>
                                <Input
                                    id="topic"
                                    placeholder="e.g., A trip to the fjords, Buying groceries..."
                                    value={topic}
                                    onChange={(e) => setTopic(e.target.value)}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label>Difficulty</Label>
                                <div className="flex gap-2">
                                    {(['Easy', 'Medium', 'Hard'] as const).map((level) => (
                                        <Button
                                            key={level}
                                            type="button"
                                            variant={difficulty === level ? 'default' : 'outline'}
                                            onClick={() => setDifficulty(level)}
                                            className="flex-1"
                                        >
                                            {level}
                                        </Button>
                                    ))}
                                </div>
                            </div>
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsDialogOpen(false)} disabled={isGenerating}>Cancel</Button>
                            <Button onClick={handleGenerate} disabled={isGenerating || !topic.trim()}>
                                {isGenerating ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Generating...</> : 'Generate Story'}
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>

            {isLoading ? (
                <div className="flex justify-center p-12"><Loader2 className="w-8 h-8 animate-spin text-muted-foreground" /></div>
            ) : stories.length === 0 ? (
                <div className="text-center py-12 border-2 border-dashed rounded-lg">
                    <BookOpen className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="text-lg font-medium">No stories yet</h3>
                    <p className="text-muted-foreground mb-4">Generate your first AI story to get started.</p>
                    <Button variant="secondary" onClick={() => setIsDialogOpen(true)}>Create Story</Button>
                </div>
            ) : (
                <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                    {stories.map((story, idx) => {
                        const gradient = GRADIENTS[idx % GRADIENTS.length]
                        const Icon = ICONS[idx % ICONS.length]

                        return (
                            <Card
                                key={story.id}
                                className="cursor-pointer hover:shadow-lg transition-all hover:scale-[1.02] border-2 hover:border-primary/50 group overflow-hidden relative"
                                onClick={() => navigate(`/smart-reading/${story.id}`)}
                            >
                                <Button
                                    variant="ghost"
                                    size="icon"
                                    className="absolute top-2 right-2 text-white/50 hover:text-white hover:bg-black/20 z-20"
                                    onClick={(e) => handleDelete(e, story.id)}
                                >
                                    <Trash2 className="w-4 h-4" />
                                </Button>

                                <div className={cn("h-32 w-full bg-gradient-to-br p-6 text-white flex flex-col justify-end", gradient)}>
                                    <Icon className="w-8 h-8 mb-2 opacity-80" />
                                    <h2 className="text-2xl font-bold truncate" title={story.title}>{story.title}</h2>
                                </div>
                                <CardContent className="p-6">
                                    <div className="flex justify-between items-center mb-4">
                                        <Badge variant={story.difficulty === 'Easy' ? 'secondary' : 'outline'}>
                                            {story.difficulty}
                                        </Badge>
                                        <span className="text-sm text-muted-foreground font-medium flex items-center gap-1">
                                            <BookOpen className="w-3 h-3" /> {(story.vocab || []).length} words
                                        </span>
                                    </div>
                                    <p className="text-sm text-muted-foreground line-clamp-2 leading-relaxed">
                                        {story.content.replace(/{{|}}/g, '')}
                                    </p>
                                </CardContent>
                            </Card>
                        )
                    })}
                </div>
            )}
        </div>
    )
}
