import React, { useEffect, useState } from "react";
import { useForm } from "@inertiajs/react";
import { PageProps } from "@/types";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Table,
    TableHeader,
    TableRow,
    TableHead,
    TableBody,
    TableCell,
} from "@/components/ui/table";
// import { toast } from "react-toastify";
import { useToast } from "@/hooks/use-toast";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import {
    Dialog,
    DialogTrigger,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import {
    Search,
    Plus,
    Pencil,
    Trash2,
    ChevronLeft,
    ChevronRight,
} from "lucide-react";
import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Head } from "@inertiajs/react";
import { Toaster } from "@/components/ui/toaster";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";

interface JenisSanksi {
    JenisSanksiId: number | null;
    NamaJenisSanksi: string;
}

const ITEMS_PER_PAGE = 5;

export default function JenisSanksiIndex({
    jenissanksi,
}: PageProps<{ jenissanksi: JenisSanksi[] }>) {
    const {
        data,
        setData,
        post,
        put,
        delete: destroy,
        reset,
    } = useForm<JenisSanksi>({
        JenisSanksiId: null,
        NamaJenisSanksi: "",
    });

    const { toast } = useToast();

    const [editing, setEditing] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [deleteConfirm, setDeleteConfirm] = useState<JenisSanksi | null>(
        null
    );
    const [search, setSearch] = useState("");

    const [filteredJenisSanksi, setFilteredJenisSanksi] = useState(jenissanksi);
    const [currentPage, setCurrentPage] = useState(1);

    useEffect(() => {
        let filtered = jenissanksi;

        if (search) {
            filtered = filtered.filter((jenissanksi) =>
                jenissanksi.NamaJenisSanksi.toLowerCase().includes(
                    search.toLowerCase()
                )
            );
        }

        setFilteredJenisSanksi(filtered);
        setCurrentPage(1);
    }, [jenissanksi, search]);

    const totalPages = Math.ceil(filteredJenisSanksi.length / ITEMS_PER_PAGE);
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    const currentItems = filteredJenisSanksi.slice(startIndex, endIndex);

    const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
        setSearch(e.target.value);
    };

    const handlePageChange = (page: number) => {
        setCurrentPage(page);
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        if (editing) {
            put(`/admin/jenissanksi/${data.JenisSanksiId}`, {
                onSuccess: () => {
                    toast({
                        title: "Berhasil",
                        description: "Jenis Sanksi berhasil diperbarui",
                        variant: "default",
                    });
                    setIsModalOpen(false);
                    reset();
                    setEditing(false);
                },
                onError: () => {
                    toast({
                        title: "Gagal",
                        description:
                            "Terjadi kesalahan saat memperbarui Jenis Sanksi",
                        variant: "destructive",
                    });
                },
            });
        } else {
            post("/admin/jenissanksi", {
                onSuccess: () => {
                    toast({
                        title: "Berhasil",
                        description: "Jenis Sanksi berhasil dibuat",
                        variant: "default",
                    });
                    setIsModalOpen(false);
                    reset();
                },
                onError: () => {
                    toast({
                        title: "Gagal",
                        description:
                            "Terjadi kesalahan saat membuat Jenis Sanksi",
                        variant: "destructive",
                    });
                },
            });
        }
    };

    const handleEdit = (jenissanksi: JenisSanksi) => {
        setData({ ...jenissanksi });
        setEditing(true);
        setIsModalOpen(true);
    };

    const handleDelete = () => {
        if (deleteConfirm) {
            destroy(`/admin/jenissanksi/${deleteConfirm.JenisSanksiId}`, {
                onSuccess: () => {
                    toast({
                        title: "Berhasil",
                        description: "Jenis Sanksi berhasil dihapus",
                        variant: "default",
                    });
                    setDeleteConfirm(null);
                },
                onError: () => {
                    toast({
                        title: "Gagal",
                        description:
                            "Terjadi kesalahan saat menghapus Jenis Sanksi",
                        variant: "destructive",
                    });
                    setDeleteConfirm(null);
                },
            });
        }
    };
    return (
        <AuthenticatedLayout header={"Jenis Sanksi"}>
            <Head title="Jenis Sanksi" />
            <div className="container mx-auto p-4">
                <Card className="shadow-lg">
                    <CardHeader>
                        <div className="flex flex-col space-y-4">
                            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                                <div className="relative w-full md:w-96">
                                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-4 w-4" />
                                    <Input
                                        type="text"
                                        placeholder="Cari Jenis Sanksi..."
                                        value={search}
                                        onChange={handleSearch}
                                        className="pl-10 pr-4 w-full border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 rounded-lg"
                                    />
                                </div>
                                <Dialog
                                    open={isModalOpen}
                                    onOpenChange={setIsModalOpen}
                                >
                                    <DialogTrigger asChild>
                                        <Button
                                            onClick={() => {
                                                setEditing(false);
                                                setIsModalOpen(true);
                                            }}
                                            className="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg flex items-center gap-2 transition-colors duration-200"
                                        >
                                            <Plus className="h-4 w-4" />
                                            Buat Jenis Sanksi
                                        </Button>
                                    </DialogTrigger>

                                    <DialogContent className="sm:max-w-md">
                                        <DialogHeader>
                                            <DialogTitle className="text-xl font-semibold">
                                                {editing
                                                    ? "Ubah JenisSanksi"
                                                    : "Buat JenisSanksi"}
                                            </DialogTitle>
                                        </DialogHeader>
                                        <form
                                            onSubmit={handleSubmit}
                                            className="flex flex-col gap-4 mt-4"
                                        >
                                            <div className="space-y-2">
                                                <label className="text-sm font-medium text-gray-700">
                                                    Name
                                                </label>
                                                <Input
                                                    type="text"
                                                    placeholder="Masukkan nama JenisSanksi"
                                                    value={data.NamaJenisSanksi}
                                                    onChange={(e) =>
                                                        setData(
                                                            "NamaJenisSanksi",
                                                            e.target.value
                                                        )
                                                    }
                                                    className="w-full"
                                                />
                                                {/* <div className="space-y-2">
                                                    <label className="text-sm font-medium text-gray-700">
                                                        Publish
                                                    </label>
                                                    <Select
                                                        value={
                                                            data.is_publish
                                                                ? "true"
                                                                : "false"
                                                        }
                                                        onValueChange={(
                                                            value
                                                        ) =>
                                                            setData(
                                                                "is_publish",
                                                                value === "true"
                                                            )
                                                        }
                                                    >
                                                        <SelectTrigger className="w-full">
                                                            <SelectValue placeholder="Select status" />
                                                        </SelectTrigger>
                                                        <SelectContent>
                                                            <SelectItem value="true">
                                                                Published
                                                            </SelectItem>
                                                            <SelectItem value="false">
                                                                Unpublished
                                                            </SelectItem>
                                                        </SelectContent>
                                                    </Select>
                                                </div> */}
                                            </div>
                                            <DialogFooter className="mt-6">
                                                <Button
                                                    type="submit"
                                                    className="w-full bg-blue-600 hover:bg-blue-700 text-white"
                                                >
                                                    {editing ? "Ubah" : "Buat"}
                                                </Button>
                                            </DialogFooter>
                                        </form>
                                    </DialogContent>
                                </Dialog>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <div className="rounded-lg border border-gray-200 overflow-hidden">
                            <Table>
                                <TableHeader>
                                    <TableRow className="bg-gray-50 dark:bg-black/50">
                                        {/* <TableHead className="font-semibold">
                                            ID
                                        </TableHead> */}
                                        <TableHead className="font-semibold">
                                            No
                                        </TableHead>
                                        <TableHead className="font-semibold">
                                            Name
                                        </TableHead>
                                        <TableHead className="font-semibold">
                                            Actions
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {currentItems.map((jenissanksi, index) => (
                                        <TableRow
                                            key={
                                                jenissanksi.JenisSanksiId ||
                                                "new"
                                            }
                                            className="hover:bg-gray-50 transition-colors duration-150"
                                        >
                                            {/* <TableCell>{category.id}</TableCell> */}
                                            <TableCell>
                                                {startIndex + index + 1}
                                            </TableCell>
                                            <TableCell>
                                                {jenissanksi.NamaJenisSanksi}
                                            </TableCell>
                                            <TableCell className="flex gap-2">
                                                <Button
                                                    onClick={() =>
                                                        handleEdit(jenissanksi)
                                                    }
                                                    variant="outline"
                                                    className="flex items-center gap-2"
                                                >
                                                    <Pencil className="h-4 w-4" />
                                                    Edit
                                                </Button>
                                                <Button
                                                    onClick={() =>
                                                        setDeleteConfirm(
                                                            jenissanksi
                                                        )
                                                    }
                                                    variant="destructive"
                                                    className="flex items-center gap-2"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                    Delete
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                    {currentItems.length === 0 && (
                                        <TableRow>
                                            <TableCell
                                                colSpan={4}
                                                className="text-center py-4 text-gray-500"
                                            >
                                                Tidak ada data
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                        {/* <div className="flex flex-row mt-3">
                            <div className="text-sm w-1/2">
                                1 : Pengumuman <br /> 2 : Undangan
                            </div>
                            <div className="text-sm w-1/2">
                                3 : Peraturan <br /> 4 : Popup Home
                            </div>
                        </div> */}
                        <div className="flex items-center justify-between mt-4">
                            <div className="text-sm text-gray-500">
                                Showing {startIndex + 1} to{" "}
                                {Math.min(endIndex, filteredJenisSanksi.length)}{" "}
                                of {filteredJenisSanksi.length} entries
                            </div>
                            <div className="flex items-center gap-2">
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() =>
                                        handlePageChange(currentPage - 1)
                                    }
                                    disabled={currentPage === 1}
                                >
                                    <ChevronLeft className="h-4 w-4" />
                                </Button>
                                {Array.from(
                                    { length: totalPages },
                                    (_, i) => i + 1
                                ).map((page) => (
                                    <Button
                                        key={page}
                                        variant={
                                            currentPage === page
                                                ? "default"
                                                : "outline"
                                        }
                                        size="sm"
                                        onClick={() => handlePageChange(page)}
                                    >
                                        {page}
                                    </Button>
                                ))}
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() =>
                                        handlePageChange(currentPage + 1)
                                    }
                                    disabled={currentPage === totalPages}
                                >
                                    <ChevronRight className="h-4 w-4" />
                                </Button>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {deleteConfirm && (
                <Dialog open={true} onOpenChange={() => setDeleteConfirm(null)}>
                    <DialogContent className="sm:max-w-md">
                        <DialogHeader>
                            <DialogTitle className="text-xl font-semibold">
                                Konfirmasi Penghapusan
                            </DialogTitle>
                        </DialogHeader>
                        <div className="py-4">
                            <p className="text-gray-600">
                                Apakah Anda yakin ingin menghapus "
                                <span className="font-medium">
                                    {deleteConfirm.NamaJenisSanksi}
                                </span>
                                "?
                                <br />
                                <span className="text-red-500">
                                    Tindakan ini tidak dapat dibatalkan.
                                </span>
                            </p>
                        </div>
                        <DialogFooter className="gap-2">
                            <Button
                                onClick={() => setDeleteConfirm(null)}
                                variant="outline"
                            >
                                Batal
                            </Button>
                            <Button
                                onClick={handleDelete}
                                variant="destructive"
                                className="flex items-center gap-2"
                            >
                                <Trash2 className="h-4 w-4" />
                                Ya, hapus
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            )}
            <Toaster />
        </AuthenticatedLayout>
    );
}
