import { useState } from 'react'
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table"
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { MoreHorizontal, Pencil, Trash2, Plus, Tag as TagIcon } from "lucide-react"
import { useTags, useDeleteTag } from "../hooks/useTags"
import { TagForm } from "./TagForm"
import type { Tag } from "@/types/api"
import { showConfirm, showToast } from "@/lib/sweetalert"

export function TagList() {
    const [selectedTag, setSelectedTag] = useState<Tag | undefined>(undefined)
    const [isDialogOpen, setIsDialogOpen] = useState(false)
    // const [page, setPage] = useState(1) // Pagination not used yet for flat array
    const page = 1

    // Assuming implementation is trying to be compatible with both
    const { data, isLoading, isError } = useTags(page, 100)
    const deleteTag = useDeleteTag()

    const handleDelete = async (id: string) => {
        const confirmed = await showConfirm(
            "Etiketi Sil?",
            "Bu etiketi silmek istediğinize emin misiniz?",
            "Evet, Sil"
        )
        if (confirmed) {
            deleteTag.mutate(id, {
                onSuccess: () => showToast("Etiket başarıyla silindi.", "success"),
                onError: () => showToast("Silme işlemi başarısız.", "error")
            })
        }
    }

    const openEditModal = (tag: Tag) => {
        setSelectedTag(tag)
        setIsDialogOpen(true)
    }

    const openCreateModal = () => {
        setSelectedTag(undefined)
        setIsDialogOpen(true)
    }

    const handleFormSuccess = () => {
        setIsDialogOpen(false)
    }

    if (isLoading) return <div>Yükleniyor...</div>
    if (isError) return <div>Hata oluştu.</div>

    // Handle both PaginatedResponse and Array just in case
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const tags: Tag[] = Array.isArray(data) ? data : (data as any)?.data || (data as any)?.tags || []

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-end">
                <Button onClick={openCreateModal}>
                    <Plus className="mr-2 h-4 w-4" /> Yeni Etiket
                </Button>
            </div>

            <div className="rounded-md border bg-white dark:bg-gray-800">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Etiket</TableHead>
                            <TableHead>Durum</TableHead>
                            <TableHead>Oluşturulma Tarihi</TableHead>
                            <TableHead className="text-right">İşlemler</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {tags.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={4} className="text-center py-8 text-muted-foreground">
                                    Kayıtlı etiket bulunamadı.
                                </TableCell>
                            </TableRow>
                        ) : (
                            tags.map((tag) => (
                                <TableRow key={tag.id}>
                                    <TableCell className="font-medium flex items-center gap-2">
                                        <TagIcon className="w-4 h-4 text-blue-500" />
                                        <span className="font-mono bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 px-2 py-1 rounded">
                                            {tag.tag}
                                        </span>
                                    </TableCell>
                                    <TableCell>
                                        {tag.is_active ? (
                                            <Badge className="bg-green-600 hover:bg-green-700">Aktif</Badge>
                                        ) : (
                                            <Badge variant="secondary">Pasif</Badge>
                                        )}
                                    </TableCell>
                                    <TableCell className="text-sm text-muted-foreground">
                                        {new Date(tag.created_at).toLocaleDateString("tr-TR")}
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" className="h-8 w-8 p-0">
                                                    <span className="sr-only">Menü</span>
                                                    <MoreHorizontal className="h-4 w-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuLabel>İşlemler</DropdownMenuLabel>
                                                <DropdownMenuItem onClick={() => openEditModal(tag)}>
                                                    <Pencil className="mr-2 h-4 w-4" /> Düzenle
                                                </DropdownMenuItem>
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem onClick={() => handleDelete(tag.id)} className="text-red-600 focus:text-red-600">
                                                    <Trash2 className="mr-2 h-4 w-4" /> Sil
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="sm:max-w-[500px]">
                    <DialogHeader>
                        <DialogTitle>{selectedTag ? "Etiketi Düzenle" : "Yeni Etiket Ekle"}</DialogTitle>
                        <DialogDescription>
                            Sistemdeki etiket tanımlarını yönetin.
                        </DialogDescription>
                    </DialogHeader>
                    <TagForm tag={selectedTag} onSuccess={handleFormSuccess} />
                </DialogContent>
            </Dialog>
        </div>
    )
}
