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 HistoryKegiatan {
    HistoryKegiatanId: number | null;
    NamaHistoryKegiatan: string;
}

const ITEMS_PER_PAGE = 5;

export default function HistoryKegiatanIndex({
    historykegiatan,
}: PageProps<{ historykegiatan: HistoryKegiatan[] }>) {
    const {
        data,
        setData,
        post,
        put,
        delete: destroy,
        reset,
    } = useForm<HistoryKegiatan>({
        HistoryKegiatanId: null,
        NamaHistoryKegiatan: "",
    });

    const { toast } = useToast();

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

    const [filteredHistoryKegiatan, setFilteredHistoryKegiatan] =
        useState(historykegiatan);
    const [currentPage, setCurrentPage] = useState(1);

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

        if (search) {
            filtered = filtered.filter((historykegiatan) =>
                historykegiatan.NamaHistoryKegiatan.toLowerCase().includes(
                    search.toLowerCase()
                )
            );
        }

        setFilteredHistoryKegiatan(filtered);
        setCurrentPage(1);
    }, [historykegiatan, search]);

    const totalPages = Math.ceil(
        filteredHistoryKegiatan.length / ITEMS_PER_PAGE
    );
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    const currentItems = filteredHistoryKegiatan.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/historykegiatan/${data.HistoryKegiatanId}`, {
                onSuccess: () => {
                    toast({
                        title: "Berhasil",
                        description: "History Kegiatan berhasil diperbarui",
                        variant: "default",
                    });
                    setIsModalOpen(false);
                    reset();
                    setEditing(false);
                },
                onError: () => {
                    toast({
                        title: "Gagal",
                        description:
                            "Terjadi kesalahan saat memperbarui History Kegiatan",
                        variant: "destructive",
                    });
                },
            });
        } else {
            post("/admin/historykegiatan", {
                onSuccess: () => {
                    toast({
                        title: "Berhasil",
                        description: "History Kegiatan berhasil dibuat",
                        variant: "default",
                    });
                    setIsModalOpen(false);
                    reset();
                },
                onError: () => {
                    toast({
                        title: "Gagal",
                        description:
                            "Terjadi kesalahan saat membuat History Kegiatan",
                        variant: "destructive",
                    });
                },
            });
        }
    };

    const handleEdit = (historykegiatan: HistoryKegiatan) => {
        setData({ ...historykegiatan });
        setEditing(true);
        setIsModalOpen(true);
    };

    const handleDelete = () => {
        if (deleteConfirm) {
            destroy(
                `/admin/historykegiatan/${deleteConfirm.HistoryKegiatanId}`,
                {
                    onSuccess: () => {
                        toast({
                            title: "Berhasil",
                            description: "History Kegiatan berhasil dihapus",
                            variant: "default",
                        });
                        setDeleteConfirm(null);
                    },
                    onError: () => {
                        toast({
                            title: "Gagal",
                            description:
                                "Terjadi kesalahan saat menghapus History Kegiatan",
                            variant: "destructive",
                        });
                        setDeleteConfirm(null);
                    },
                }
            );
        }
    };
    return (
        <AuthenticatedLayout header={"History Kegiatan"}>
            <Head title="History Kegiatan" />
            <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 History Kegiatan..."
                                        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 History Kegiatan
                                        </Button>
                                    </DialogTrigger>

                                    <DialogContent className="sm:max-w-md">
                                        <DialogHeader>
                                            <DialogTitle className="text-xl font-semibold">
                                                {editing
                                                    ? "Ubah History Kegiatan"
                                                    : "Buat History Kegiatan"}
                                            </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 History Kegiatan"
                                                    value={
                                                        data.NamaHistoryKegiatan
                                                    }
                                                    onChange={(e) =>
                                                        setData(
                                                            "NamaHistoryKegiatan",
                                                            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(
                                        (historykegiatan, index) => (
                                            <TableRow
                                                key={
                                                    historykegiatan.HistoryKegiatanId ||
                                                    "new"
                                                }
                                                className="hover:bg-gray-50 transition-colors duration-150"
                                            >
                                                {/* <TableCell>{category.id}</TableCell> */}
                                                <TableCell>
                                                    {startIndex + index + 1}
                                                </TableCell>
                                                <TableCell>
                                                    {
                                                        historykegiatan.NamaHistoryKegiatan
                                                    }
                                                </TableCell>
                                                <TableCell className="flex gap-2">
                                                    <Button
                                                        onClick={() =>
                                                            handleEdit(
                                                                historykegiatan
                                                            )
                                                        }
                                                        variant="outline"
                                                        className="flex items-center gap-2"
                                                    >
                                                        <Pencil className="h-4 w-4" />
                                                        Edit
                                                    </Button>
                                                    <Button
                                                        onClick={() =>
                                                            setDeleteConfirm(
                                                                historykegiatan
                                                            )
                                                        }
                                                        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,
                                    filteredHistoryKegiatan.length
                                )}{" "}
                                of {filteredHistoryKegiatan.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.NamaHistoryKegiatan}
                                </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>
    );
}
