import React, { useEffect, useState } from "react";
import { useForm } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Table,
    TableHeader,
    TableRow,
    TableHead,
    TableBody,
    TableCell,
} from "@/components/ui/table";
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 axios from "axios";

interface Hukum {
    HukumId: number;
    PerusahaanId: number | null;
    JenisSanksiId: number | null;
    SanksiNumber: string;
    SanksiDate: string;
    SanksiFile: string;
    StatusPenaatan: number;
    PenaatanNumber: string;
    PenaatanDate: string;
    PenaatanFile: string;
    IsDeleted: number;
    perusahaan: { nama: string } | null;
    jenisSanksi: { nama: string } | null;
}

const ITEMS_PER_PAGE = 5;

export default function HukumIndex() {
    const { toast } = useToast();
    const [dataHukum, setDataHukum] = useState<Hukum[]>([]);
    const [search, setSearch] = useState("");
    const [filteredHukum, setFilteredHukum] = useState<Hukum[]>([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editing, setEditing] = useState(false);
    const [deleteConfirm, setDeleteConfirm] = useState<Hukum | null>(null);

    const {
        data,
        setData,
        post,
        put,
        delete: destroy,
        reset,
    } = useForm<Hukum>({
        HukumId: 0,
        PerusahaanId: null,
        JenisSanksiId: null,
        SanksiNumber: "",
        SanksiDate: "",
        SanksiFile: "",
        StatusPenaatan: 1,
        PenaatanNumber: "",
        PenaatanDate: "",
        PenaatanFile: "",
        IsDeleted: 0,
        perusahaan: null,
        jenisSanksi: null,
    });

    useEffect(() => {
        axios
            .get("/admin/hukum")
            .then((response) => {
                if (response.data && response.data.data) {
                    setDataHukum(response.data.data);
                    setFilteredHukum(response.data.data);
                } else {
                    setDataHukum([]);
                    setFilteredHukum([]);
                }
            })
            .catch((error) => {
                console.error("Error fetching data:", error);
                setDataHukum([]);
                setFilteredHukum([]);
            });
    }, []);

    // Filter Data
    useEffect(() => {
        let filtered = dataHukum;
        if (search) {
            filtered = filtered.filter((hukum) =>
                hukum.SanksiNumber.toLowerCase().includes(search.toLowerCase())
            );
        }
        setFilteredHukum(filtered);
        setCurrentPage(1);
    }, [dataHukum, search]);

    // Pagination
    const totalPages = filteredHukum?.length
        ? Math.ceil(filteredHukum.length / ITEMS_PER_PAGE)
        : 1;

    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    const currentItems = filteredHukum.slice(startIndex, endIndex);

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

    // Handle Page Change
    const handlePageChange = (page: number) => {
        setCurrentPage(page);
    };

    // Handle Form Submission
    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        const url = editing ? `/admin/hukum/${data.HukumId}` : "/admin/hukum";

        const requestMethod = editing ? put : post;
        requestMethod(url, {
            onSuccess: () => {
                toast({
                    title: "Berhasil",
                    description: editing
                        ? "Data berhasil diperbarui"
                        : "Data berhasil ditambahkan",
                    variant: "default",
                });
                setIsModalOpen(false);
                reset();
                setEditing(false);
            },
            onError: () => {
                toast({
                    title: "Gagal",
                    description: "Terjadi kesalahan saat menyimpan data",
                    variant: "destructive",
                });
            },
        });
    };

    // Handle Edit
    const handleEdit = (hukum: Hukum) => {
        setData({ ...hukum });
        setEditing(true);
        setIsModalOpen(true);
    };

    // Handle Delete
    const handleDelete = () => {
        if (deleteConfirm) {
            destroy(`/admin/hukum/${deleteConfirm.HukumId}`, {
                onSuccess: () => {
                    toast({
                        title: "Berhasil",
                        description: "Data berhasil dihapus",
                        variant: "default",
                    });
                    setDeleteConfirm(null);
                },
                onError: () => {
                    toast({
                        title: "Gagal",
                        description: "Terjadi kesalahan saat menghapus data",
                        variant: "destructive",
                    });
                },
            });
        }
    };

    return (
        <AuthenticatedLayout header="Penegakan Hukum">
            <Head title="Penegakan Hukum" />
            <div className="container mx-auto p-4">
                <Card className="shadow-lg">
                    <CardHeader>
                        <div className="flex justify-between">
                            <Input
                                type="text"
                                placeholder="Cari Sanksi..."
                                value={search}
                                onChange={handleSearch}
                            />
                            <Button
                                onClick={() => {
                                    setEditing(false);
                                    setIsModalOpen(true);
                                }}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </Button>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>No</TableHead>
                                    <TableHead>Nama Perusahaan</TableHead>
                                    <TableHead>Jenis Sanksi</TableHead>
                                    <TableHead>Nomor SK Sanksi</TableHead>
                                    <TableHead>Tanggal Sanksi</TableHead>
                                    <TableHead>SK Sanksi</TableHead>
                                    <TableHead>Status Penaatan</TableHead>
                                    <TableHead>Nomor Penaatan</TableHead>
                                    <TableHead>Tanggal Penaatan</TableHead>
                                    <TableHead>SK Penaatan</TableHead>
                                    <TableHead>Aksi</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {currentItems.map((hukum, index) => (
                                    <TableRow key={hukum.HukumId}>
                                        <TableCell>
                                            {startIndex + index + 1}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.perusahaan?.nama}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.jenisSanksi?.nama}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.SanksiNumber}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.SanksiDate}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.SanksiFile}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.StatusPenaatan}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.PenaatanNumber}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.PenaatanDate}
                                        </TableCell>
                                        <TableCell>
                                            {hukum.PenaatanFile}
                                        </TableCell>
                                        <TableCell>
                                            <Button
                                                onClick={() =>
                                                    handleEdit(hukum)
                                                }
                                            >
                                                <Pencil className="h-4 w-4" />
                                            </Button>
                                            <Button
                                                onClick={() =>
                                                    setDeleteConfirm(hukum)
                                                }
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            </div>
            <Toaster />
        </AuthenticatedLayout>
    );
}
