import { usePage, router, Link } from "@inertiajs/react";
import LayoutPrivate from "@/Layouts/Private/layout";
import SearchBar from "@/Components/SearchBar";
import DataTable from "./components/DataTable";
import Pagination from "@/Components/Pagination";
import { PageProps } from "@/types/param";
import { Card } from "@/Components/ui/card";
import { CursoMaterial } from "@/types/curso-material";
import { Button } from "@/Components/ui/button";
import { CirclePlus } from "lucide-react";
import { useCursoMaterialStore } from "@/Store/useCursoMaterialStore";
import { useState } from "react";
import { ModalDeleteCursoMaterial } from "./components/ModalDelete";

export default function Index() {
    const { auth, cursos, cursos_materiales, filters } =
        usePage<PageProps<CursoMaterial>>().props;
    const [search, setSearch] = useState<string>(filters.search || "");
    const [perPage, setPerPage] = useState<number>(filters.per_page || 10);

    const handlePerPageChange = (value: string) => {
        const perPageValue = Number(value);
        setPerPage(perPageValue);
        router.get(route("cursos-materiales.index"), {
            search,
            per_page: perPageValue,
        });
    };

    const handleSearch = (value: string) => {
        setSearch(value);
        router.get(
            route("cursos-materiales.index"),
            { search: value, perPage },
            { preserveState: true }
        );
    };

    const { openModalDeleteCursoMaterial } = useCursoMaterialStore();

    return (
        <LayoutPrivate user={auth.user} header={"Sessiones de Estudio"}>
            <div className="w-full max-w-4xl">
                <Card className="pt-4 px-4 flex gap-4">
                    <SearchBar
                        keyName="CursoMaterial"
                        className={"flex-1"}
                        search={search}
                        perPage={perPage}
                        onSearch={handleSearch}
                        onPerPageChange={handlePerPageChange}
                    />

                    <Link href={route("cursos-materiales.create")}>
                        <Button variant={"outline"}>
                            Crear <CirclePlus />
                        </Button>
                    </Link>
                </Card>
                <Card className="mt-8 px-4 pb-4">
                    <DataTable data={cursos_materiales.data} />
                    <Pagination
                        currentPage={cursos_materiales.current_page}
                        lastPage={cursos_materiales.last_page}
                        prevPageUrl={cursos_materiales.prev_page_url}
                        nextPageUrl={cursos_materiales.next_page_url}
                        search={search}
                        perPage={perPage}
                    />
                </Card>
            </div>
            {openModalDeleteCursoMaterial && <ModalDeleteCursoMaterial />}
        </LayoutPrivate>
    );
}
