import { useFlashcardSets, useCreateFlashcardSet } from '@/features/flashcards/api/queries'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { useNavigate } from 'react-router'
import { cn } from '@/lib/utils'
import { Layers, Plus, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
    DialogFooter
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useState } from 'react'

export const SetsPage = () => {
    const navigate = useNavigate()
    const { data: sets, isLoading } = useFlashcardSets()
    const createSetMutation = useCreateFlashcardSet()
    const [isDialogOpen, setIsDialogOpen] = useState(false)
    const [title, setTitle] = useState('')
    const [topic, setTopic] = useState('')

    // Random gradient generator or selector could be here.
    const getRandomGradient = () => {
        const gradients = [
            'from-blue-500 to-cyan-500',
            'from-purple-500 to-pink-500',
            'from-orange-500 to-red-500',
            'from-green-500 to-emerald-500',
            'from-indigo-500 to-violet-500'
        ]
        return gradients[Math.floor(Math.random() * gradients.length)]
    }

    const handleCreateSet = () => {
        console.log("Attempting to create set:", { title, topic });
        if (!title.trim() || !topic.trim()) {
            console.log("Validation failed: Empty fields");
            return;
        }
        createSetMutation.mutate({
            title,
            topic,
            color: getRandomGradient()
        }, {
            onSuccess: () => {
                console.log("Set created successfully");
                setIsDialogOpen(false)
                setTitle('')
                setTopic('')
            },
            onError: (error) => {
                console.error("Failed to create set:", error);
                alert(`Failed to create set: ${error}`);
            }
        })
    }

    if (isLoading) return <div className="flex justify-center items-center h-full"><Loader2 className="w-8 h-8 animate-spin" /></div>

    return (
        <div className="p-8 max-w-5xl mx-auto">
            <div className="mb-8 flex justify-between items-center">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Flashcard Sets</h1>
                    <p className="text-muted-foreground">Select a deck to start learning or create a new one.</p>
                </div>
                <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                    <DialogTrigger asChild>
                        <Button>
                            <Plus className="w-4 h-4 mr-2" /> New Deck
                        </Button>
                    </DialogTrigger>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Create New Deck</DialogTitle>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                            <div className="grid grid-cols-4 items-center gap-4">
                                <Label htmlFor="title" className="text-right">Title</Label>
                                <Input
                                    id="title"
                                    value={title}
                                    onChange={(e) => setTitle(e.target.value)}
                                    className="col-span-3"
                                    placeholder="e.g., Common Verbs"
                                />
                            </div>
                            <div className="grid grid-cols-4 items-center gap-4">
                                <Label htmlFor="topic" className="text-right">Topic</Label>
                                <Input
                                    id="topic"
                                    value={topic}
                                    onChange={(e) => setTopic(e.target.value)}
                                    className="col-span-3"
                                    placeholder="e.g., Grammar"
                                />
                            </div>
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                            <Button onClick={handleCreateSet} disabled={createSetMutation.isPending || !title.trim() || !topic.trim()}>
                                {createSetMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Create'}
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {sets?.map((set) => (
                    <Card
                        key={set.id}
                        className="cursor-pointer hover:shadow-lg transition-all hover:scale-[1.02] border-2 hover:border-primary/50 group"
                        onClick={() => navigate(`/flashcards/${set.id}`)}
                    >
                        <div className={cn("h-32 w-full bg-gradient-to-br p-6 text-white flex flex-col justify-end", set.color)}>
                            <Layers className="w-8 h-8 mb-2 opacity-80" />
                            <h2 className="text-2xl font-bold">{set.title}</h2>
                        </div>
                        <CardContent className="p-6">
                            <div className="flex justify-between items-center mb-4">
                                <Badge variant="secondary">{set.topic}</Badge>
                                <span className="text-sm text-muted-foreground font-medium">
                                    {set.cards?.length || 0} cards
                                </span>
                            </div>
                            <p className="text-sm text-muted-foreground">
                                Tap to view study options, edit cards, or check your progress.
                            </p>
                        </CardContent>
                    </Card>
                ))}

                {sets && sets.length === 0 && (
                    <div className="col-span-full text-center py-20 text-muted-foreground">
                        <p>No flashcard sets found. Create one to get started!</p>
                    </div>
                )}
            </div>
        </div>
    )
}
