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 { Input } from "@/components/ui/input"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { MoreHorizontal, Pencil, Trash2, Search, RotateCcw, Ban, Plus } from "lucide-react"
import { useUsers, useDeleteUser, useRestoreUser, useHardDeleteUser } from "../hooks/useUsers"
import { UserForm } from "./UserForm"
import type { User } from "@/types/api"
import { showConfirm, showToast } from "@/lib/sweetalert"

export function UserList() {
    const [page, setPage] = useState(1)
    const [search, setSearch] = useState("")
    const [isDeletedView, setIsDeletedView] = useState(false)
    const [selectedUser, setSelectedUser] = useState<User | undefined>(undefined)
    const [isDialogOpen, setIsDialogOpen] = useState(false)

    const { data, isLoading, isError } = useUsers(page, 10, search, isDeletedView)
    const deleteUser = useDeleteUser()
    const restoreUser = useRestoreUser()
    const hardDeleteUser = useHardDeleteUser()

    const handleDelete = async (id: string) => {
        const confirmed = await showConfirm(
            "Emin misiniz?",
            "Bu kullanıcıyı çöp kutusuna taşımak üzeresiniz.",
            "Evet, Sil",
            "İptal"
        )
        if (confirmed) {
            deleteUser.mutate(id, {
                onSuccess: () => showToast("Kullanıcı çöp kutusuna taşındı.", "success"),
                onError: () => showToast("İşlem başarısız oldu.", "error")
            })
        }
    }

    const handleRestore = async (id: string) => {
        const confirmed = await showConfirm(
            "Geri Yükle?",
            "Bu kullanıcı tekrar aktif hale getirilecek.",
            "Evet, Geri Yükle"
        )
        if (confirmed) {
            restoreUser.mutate(id, {
                onSuccess: () => showToast("Kullanıcı geri yüklendi.", "success"),
                onError: () => showToast("İşlem başarısız oldu.", "error")
            })
        }
    }

    const handleHardDelete = async (id: string) => {
        const confirmed = await showConfirm(
            "KALICI OLARAK SİLİNECEK!",
            "Bu işlem geri alınamaz. Kullanıcıyı tamamen silmek istediğinize emin misiniz?",
            "Evet, Kalıcı Sil",
            "İptal"
        )
        if (confirmed) {
            hardDeleteUser.mutate(id, {
                onSuccess: () => showToast("Kullanıcı kalıcı olarak silindi.", "success"),
                onError: () => showToast("İşlem başarısız oldu.", "error")
            })
        }
    }

    const onTabChange = (value: string) => {
        setIsDeletedView(value === 'deleted')
        setPage(1)
    }

    const openEditModal = (user: User) => {
        setSelectedUser(user)
        setIsDialogOpen(true)
    }

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

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

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

    const users = data?.users || []
    const totalPages = data?.pagination?.totalPages || 1

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-between">
                <Tabs defaultValue="active" className="w-[400px]" onValueChange={onTabChange}>
                    <TabsList>
                        <TabsTrigger value="active">Aktif Kullanıcılar</TabsTrigger>
                        <TabsTrigger value="deleted">Çöp Kutusu</TabsTrigger>
                    </TabsList>
                </Tabs>

                {!isDeletedView && (
                    <Button onClick={openCreateModal}>
                        <Plus className="mr-2 h-4 w-4" /> Yeni Kullanıcı
                    </Button>
                )}
            </div>

            <div className="flex items-center space-x-2">
                <div className="relative w-72">
                    <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                        placeholder="Kullanıcı ara..."
                        className="pl-8"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                    />
                </div>
            </div>

            <div className="rounded-md border bg-white dark:bg-gray-800">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Email</TableHead>
                            <TableHead>Kullanıcı Adı</TableHead>
                            <TableHead>Roller</TableHead>
                            <TableHead>Durum</TableHead>
                            <TableHead className="text-right">İşlemler</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {users.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                                    {isDeletedView ? "Çöp kutusu boş." : "Kullanıcı bulunamadı."}
                                </TableCell>
                            </TableRow>
                        ) : (
                            users.map((user) => (
                                <TableRow key={user.id}>
                                    <TableCell className="font-medium">{user.email}</TableCell>
                                    <TableCell>{user.user_name}</TableCell>
                                    <TableCell>
                                        {user.roles?.map(r => <Badge key={r.id} variant="outline" className="mr-1">{r.name}</Badge>) || "-"}
                                    </TableCell>
                                    <TableCell>
                                        {isDeletedView ? (
                                            <Badge variant="destructive">Silindi</Badge>
                                        ) : (
                                            user.email_verified ? (
                                                <Badge variant="default" className="bg-green-600 hover:bg-green-700">Doğrulanmış</Badge>
                                            ) : (
                                                <Badge variant="secondary">Bekliyor</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={() => {
                                                    navigator.clipboard.writeText(user.id)
                                                    showToast("ID kopyalandı")
                                                }}>
                                                    ID Kopyala
                                                </DropdownMenuItem>

                                                {!isDeletedView ? (
                                                    <>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem onClick={() => openEditModal(user)}>
                                                            <Pencil className="mr-2 h-4 w-4" /> Düzenle
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem onClick={() => handleDelete(user.id)} className="text-red-600 focus:text-red-600">
                                                            <Trash2 className="mr-2 h-4 w-4" /> Çöp Kutusuna Taşı
                                                        </DropdownMenuItem>
                                                    </>
                                                ) : (
                                                    <>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem onClick={() => handleRestore(user.id)} className="text-green-600 focus:text-green-600">
                                                            <RotateCcw className="mr-2 h-4 w-4" /> Geri Yükle
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem onClick={() => handleHardDelete(user.id)} className="text-red-700 focus:text-red-700 font-bold">
                                                            <Ban className="mr-2 h-4 w-4" /> Kalıcı Olarak Sil
                                                        </DropdownMenuItem>
                                                    </>
                                                )}

                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            <div className="flex items-center justify-end space-x-2 py-4">
                <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage(p => Math.max(1, p - 1))}
                    disabled={page === 1}
                >
                    Önceki
                </Button>
                <span className="text-sm text-muted-foreground">
                    Sayfa {page} / {totalPages}
                </span>
                <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                    disabled={page === totalPages}
                >
                    Sonraki
                </Button>
            </div>

            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="sm:max-w-[500px]">
                    <DialogHeader>
                        <DialogTitle>{selectedUser ? "Kullanıcıyı Düzenle" : "Yeni Kullanıcı Oluştur"}</DialogTitle>
                        <DialogDescription>
                            {selectedUser ? "Kullanıcı bilgilerini güncelleyin." : "Sisteme yeni bir kullanıcı ekleyin."}
                        </DialogDescription>
                    </DialogHeader>
                    <UserForm user={selectedUser} onSuccess={handleFormSuccess} />
                </DialogContent>
            </Dialog>
        </div>
    )
}
