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, FileText } from "lucide-react"
import { useAbouts, useDeleteAbout } from "../hooks/useAbout"
import { AboutForm } from "./AboutForm"
import type { About } from "@/types/api"
import { showConfirm, showToast } from "@/lib/sweetalert"
import { getMediaUrl } from "@/lib/utils"

export function AboutList() {
    const [selectedAbout, setSelectedAbout] = useState<About | undefined>(undefined)
    const [isDialogOpen, setIsDialogOpen] = useState(false)

    const { data, isLoading, isError } = useAbouts()
    const deleteMutation = useDeleteAbout()

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

    const openEditModal = (about: About) => {
        setSelectedAbout(about)
        setIsDialogOpen(true)
    }

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

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

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

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const abouts: About[] = Array.isArray(data) ? data : (data as any)?.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 Kayıt Ekle
                </Button>
            </div>

            <div className="rounded-md border bg-white dark:bg-gray-800">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Başlık</TableHead>
                            <TableHead>Görsel</TableHead>
                            <TableHead>Şehir</TableHead>
                            <TableHead>Meslek/Ünvan</TableHead>
                            <TableHead>Durum</TableHead>
                            <TableHead className="text-right">İşlemler</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {abouts.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                                    Kayıt bulunamadı.
                                </TableCell>
                            </TableRow>
                        ) : (
                            abouts.map((about) => (
                                <TableRow key={about.id}>
                                    <TableCell className="font-medium">
                                        {about.title}
                                    </TableCell>
                                    <TableCell>
                                        {about.image ? (
                                            <img src={getMediaUrl(about.image)} alt="Profile" className="w-8 h-8 rounded-full object-cover" />
                                        ) : (
                                            <span className="text-muted-foreground">-</span>
                                        )}
                                    </TableCell>
                                    <TableCell>{about.city || "-"}</TableCell>
                                    <TableCell>{about.image_sub || "-"}</TableCell>
                                    <TableCell>
                                        {about.is_active ? (
                                            <Badge className="bg-green-600 hover:bg-green-700">Aktif</Badge>
                                        ) : (
                                            <Badge variant="secondary">Pasif</Badge>
                                        )}
                                    </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(about)}>
                                                    <Pencil className="mr-2 h-4 w-4" /> Düzenle
                                                </DropdownMenuItem>
                                                {about.cv && (
                                                    <DropdownMenuItem asChild>
                                                        <a href={getMediaUrl(about.cv)} target="_blank" rel="noreferrer" className="cursor-pointer">
                                                            <FileText className="mr-2 h-4 w-4" /> CV İndir
                                                        </a>
                                                    </DropdownMenuItem>
                                                )}
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem onClick={() => handleDelete(about.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-[900px]">
                    <DialogHeader>
                        <DialogTitle>{selectedAbout ? "Kayıt Düzenle" : "Yeni Kayıt Ekle"}</DialogTitle>
                        <DialogDescription>
                            Hakkımda sayfası için içerik yönetimi.
                        </DialogDescription>
                    </DialogHeader>
                    <AboutForm about={selectedAbout} onSuccess={handleFormSuccess} />
                </DialogContent>
            </Dialog>
        </div>
    )
}
