import { useNavigate, useParams } from 'react-router'
import { useFlashcardSet, useCreateFlashcard, useUpdateFlashcard, useDeleteFlashcard } from '@/features/flashcards/api/queries'
import { Button } from '@/components/ui/button'
import { ArrowLeft, ArrowDownCircle, Search, Plus, Trash2, Edit2, Loader2, Save } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
    DialogFooter
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { useQueryClient } from '@tanstack/react-query'

export const SetListPage = () => {
    const { setId } = useParams()
    const navigate = useNavigate()
    const { data: set, isLoading } = useFlashcardSet(setId || '')
    const createCardMutation = useCreateFlashcard()
    const updateCardMutation = useUpdateFlashcard()
    const deleteCardMutation = useDeleteFlashcard()

    const [searchTerm, setSearchTerm] = useState('')
    const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
    const [editingCardId, setEditingCardId] = useState<string | null>(null)

    // Form state
    const [front, setFront] = useState('')
    const [back, setBack] = useState('')

    const filteredCards = useMemo(() => {
        if (!set?.cards) return []
        if (!searchTerm) return set.cards
        return set.cards.filter(c =>
            c.front.toLowerCase().includes(searchTerm.toLowerCase()) ||
            c.back.toLowerCase().includes(searchTerm.toLowerCase())
        )
    }, [set, searchTerm])

    const handleAddCard = () => {
        if (!setId || !front.trim() || !back.trim()) return
        createCardMutation.mutate({ setId, front, back }, {
            onSuccess: () => {
                setIsAddDialogOpen(false)
                setFront('')
                setBack('')
            }
        })
    }

    const startEditing = (card: any) => {
        setEditingCardId(card.id)
        setFront(card.front)
        setBack(card.back)
        setIsAddDialogOpen(true)
    }

    const handleUpdateCard = () => {
        if (!setId || !editingCardId || !front.trim() || !back.trim()) return
        updateCardMutation.mutate({ id: editingCardId, setId, front, back }, {
            onSuccess: () => {
                setIsAddDialogOpen(false)
                setEditingCardId(null)
                setFront('')
                setBack('')
            }
        })
    }

    const handleSave = () => {
        if (editingCardId) {
            handleUpdateCard()
        } else {
            handleAddCard()
        }
    }

    const handleDelete = (id: string, e: React.MouseEvent) => {
        e.stopPropagation()
        if (!setId) return
        if (confirm('Are you sure you want to delete this card?')) {
            deleteCardMutation.mutate({ id, setId })
        }
    }

    const openAddDialog = () => {
        setEditingCardId(null)
        setFront('')
        setBack('')
        setIsAddDialogOpen(true)
    }

    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 className="p-8">Set not found</div>

    return (
        <div className="flex flex-col min-h-screen p-4 md:p-8 max-w-4xl mx-auto">
            <motion.div
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                className="mb-8 space-y-4"
            >
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <Button variant="ghost" className="-ml-3" onClick={() => navigate('/flashcards')}>
                            <ArrowLeft className="w-5 h-5 mr-2" /> Back
                        </Button>
                    </div>
                    <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
                        <DialogTrigger asChild>
                            <Button onClick={openAddDialog}>
                                <Plus className="w-4 h-4 mr-2" /> Add Card
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>{editingCardId ? 'Edit Card' : 'Add New Card'}</DialogTitle>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="front">Front (Question)</Label>
                                    <Input
                                        id="front"
                                        value={front}
                                        onChange={(e) => setFront(e.target.value)}
                                        placeholder="e.g., God morgen"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="back">Back (Answer)</Label>
                                    <Input
                                        id="back"
                                        value={back}
                                        onChange={(e) => setBack(e.target.value)}
                                        placeholder="e.g., Good morning"
                                    />
                                </div>
                            </div>
                            <DialogFooter>
                                <Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>Cancel</Button>
                                <Button onClick={handleSave} disabled={createCardMutation.isPending || updateCardMutation.isPending}>
                                    {(createCardMutation.isPending || updateCardMutation.isPending) && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                    Save
                                </Button>
                            </DialogFooter>
                        </DialogContent>
                    </Dialog>
                </div>

                <div>
                    <h1 className="text-3xl font-black tracking-tight">{set.title}</h1>
                    <p className="text-muted-foreground font-medium flex items-center gap-2 mt-1">
                        <span className="w-8 h-[2px] bg-primary/20 block" />
                        List View ({set.cards?.length || 0} cards)
                    </p>
                </div>

                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                        placeholder="Filter cards..."
                        className="pl-9 bg-card/50 backdrop-blur-sm border-2 focus-visible:ring-offset-0 focus-visible:ring-2 focus-visible:ring-primary/20"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>
            </motion.div>

            <div className="space-y-3 pb-20">
                <AnimatePresence mode="popLayout">
                    {filteredCards.map((card, idx) => (
                        <motion.div
                            key={`${card.id}-${idx}`}
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, scale: 0.95 }}
                            transition={{ delay: idx * 0.05 }}
                            layout
                            className="group bg-card hover:bg-accent/5 transition-colors border rounded-xl p-4 md:p-6 shadow-sm flex flex-col md:flex-row md:items-center gap-4 relative"
                        >
                            <div className="flex-1 font-medium text-lg text-primary/90">
                                {card.front}
                            </div>

                            <div className="hidden md:flex items-center justify-center text-muted-foreground/30">
                                <ArrowDownCircle className="w-6 h-6 -rotate-90 group-hover:text-primary/50 transition-colors" />
                            </div>
                            <div className="md:hidden flex items-center justify-center text-muted-foreground/30 py-2">
                                <ArrowDownCircle className="w-6 h-6 group-hover:text-primary/50 transition-colors" />
                            </div>

                            <div className="flex-1 md:text-right font-bold text-xl text-primary">
                                {card.back}
                            </div>

                            <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-2">
                                <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-primary" onClick={() => startEditing(card)}>
                                    <Edit2 className="w-4 h-4" />
                                </Button>
                                <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10" onClick={(e) => handleDelete(card.id, e)}>
                                    <Trash2 className="w-4 h-4" />
                                </Button>
                            </div>
                        </motion.div>
                    ))}
                </AnimatePresence>

                {filteredCards.length === 0 && (
                    <div className="text-center py-20 text-muted-foreground">
                        No cards found matching your search.
                    </div>
                )}
            </div>
        </div>
    )
}
