import { useState } from 'react'
import { getMediaUrl } from "@/lib/utils"
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, LayoutTemplate, ExternalLink } from "lucide-react"
import { useHomes, useDeleteHome } from "../hooks/useHomes"
import { HomeForm } from "./HomeForm"
import type { Home } from "@/types/api"
import { showConfirm, showToast } from "@/lib/sweetalert"

export function HomeList() {
    const [selectedHome, setSelectedHome] = useState<Home | undefined>(undefined)
    const [isDialogOpen, setIsDialogOpen] = useState(false)

    // Assuming backend returns array or PaginatedResponse
    const { data, isLoading, isError } = useHomes()
    const deleteHome = useDeleteHome()

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

    const openEditModal = (home: Home) => {
        setSelectedHome(home)
        setIsDialogOpen(true)
    }

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

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

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

    // Handle array or paginated response
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const homes: Home[] = 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 İçerik Ekle
                </Button>
            </div>

            <div className="rounded-md border bg-white dark:bg-gray-800">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>İsim (Slug)</TableHead>
                            <TableHead>Başlık</TableHead>
                            <TableHead>Etiketler</TableHead>
                            <TableHead>Görsel</TableHead>
                            <TableHead>Durum</TableHead>
                            <TableHead className="text-right">İşlemler</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {homes.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                                    Kayıtlı içerik bulunamadı.
                                </TableCell>
                            </TableRow>
                        ) : (
                            homes.map((home) => (
                                <TableRow key={home.id}>
                                    <TableCell className="font-medium flex items-center gap-2">
                                        <LayoutTemplate className="w-4 h-4 text-gray-500" />
                                        {home.name}
                                    </TableCell>
                                    <TableCell>{home.title}</TableCell>
                                    <TableCell>
                                        <div className="flex flex-wrap gap-1">
                                            {home.tags && home.tags.length > 0 ? (
                                                home.tags.map(tag => (
                                                    <Badge key={tag.id} variant="outline" className="text-xs">
                                                        {tag.tag}
                                                    </Badge>
                                                ))
                                            ) : (
                                                <span className="text-xs text-muted-foreground">-</span>
                                            )}
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        {home.image ? (
                                            <a href={getMediaUrl(home.image)} target="_blank" rel="noreferrer" className="text-blue-500 hover:underline text-xs flex items-center">
                                                <ExternalLink className="w-3 h-3 mr-1" /> Görsel
                                            </a>
                                        ) : (
                                            <span className="text-xs text-muted-foreground">-</span>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        {home.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(home)}>
                                                    <Pencil className="mr-2 h-4 w-4" /> Düzenle
                                                </DropdownMenuItem>
                                                <DropdownMenuSeparator />
                                                <DropdownMenuItem onClick={() => handleDelete(home.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-[600px]">
                    <DialogHeader>
                        <DialogTitle>{selectedHome ? "İçeriği Düzenle" : "Yeni İçerik Ekle"}</DialogTitle>
                        <DialogDescription>
                            Anasayfa slider veya banner alanları için içerik yönetimi.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="max-h-[80vh] overflow-y-auto pr-2">
                        <HomeForm home={selectedHome} onSuccess={handleFormSuccess} />
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    )
}
