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 } from "lucide-react"
import { useCorsRules, useDeleteCorsRule } from "../hooks/useCors"
import { CorsForm } from "./CorsForm"
import type { CorsRule } from "@/types/api"
import { showConfirm, showToast } from "@/lib/sweetalert"

interface CorsListProps {
    type: 'whitelist' | 'blacklist'
}

export function CorsList({ type }: CorsListProps) {
    const [selectedRule, setSelectedRule] = useState<CorsRule | undefined>(undefined)
    const [isDialogOpen, setIsDialogOpen] = useState(false)

    // No pagination support in backend for now
    const { data, isLoading, isError } = useCorsRules(type)
    const deleteRule = useDeleteCorsRule(type)

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

    const openEditModal = (rule: CorsRule) => {
        setSelectedRule(rule)
        setIsDialogOpen(true)
    }

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

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

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

    // Backend endpoint returns an array directly, not PaginatedResponse
    const rules = Array.isArray(data) ? data : []

    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 {type === 'whitelist' ? 'Whitelist' : 'Blacklist'} Kuralı
                </Button>
            </div>

            <div className="rounded-md border bg-white dark:bg-gray-800">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Origin</TableHead>
                            <TableHead>Açıklama</TableHead>
                            <TableHead>Durum</TableHead>
                            <TableHead>Oluşturulma Tarihi</TableHead>
                            <TableHead className="text-right">İşlemler</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {rules.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                                    Kural bulunamadı.
                                </TableCell>
                            </TableRow>
                        ) : (
                            rules.map((rule) => (
                                <TableRow key={rule.id}>
                                    <TableCell className="font-medium font-mono">{rule.origin}</TableCell>
                                    <TableCell>{rule.description || "-"}</TableCell>
                                    <TableCell>
                                        {rule.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(rule.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(rule)}>
                                                    <Pencil className="mr-2 h-4 w-4" /> Düzenle
                                                </DropdownMenuItem>
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem onClick={() => handleDelete(rule.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>{selectedRule ? "Kuralı Düzenle" : "Yeni Kural Ekle"}</DialogTitle>
                        <DialogDescription>
                            {type === 'whitelist' ? 'İzin verilen' : 'Engellenen'} kaynak erişim kuralını yapılandırın.
                        </DialogDescription>
                    </DialogHeader>
                    <CorsForm type={type} rule={selectedRule} onSuccess={handleFormSuccess} />
                </DialogContent>
            </Dialog>
        </div>
    )
}
