import {
    AlertDialog,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import { Button } from "@/Components/ui/button";
import { useGradoStore } from "@/Store/useGradoStore";
import { useForm } from "@inertiajs/react";
import { toast } from "sonner";
import { Page } from "@inertiajs/core";

export function ModalDeleteGrado() {
    const { grado, openModalDeleteGrado, setOpenModalDeleteGrado } =
        useGradoStore();
    const { delete: destroy, processing } = useForm();

    const handleDelete = () => {
        if (!grado?.id) return;

        destroy(route("grados.destroy", grado.id), {
            preserveScroll: true,
            onSuccess: (response: Page<{ status?: { success?: string } }>) => {
                const successMessage =
                    response.props?.status?.success ??
                    "Grado eliminado correctamente.";
                toast.success(successMessage);
                setOpenModalDeleteGrado(false);
            },
            onError: (response: {
                props?: { status?: { error?: string } };
            }) => {
                const errorMessage =
                    response?.props?.status?.error || "Error en el formulario.";
                toast.error(errorMessage);
            },
        });
    };

    return (
        <AlertDialog
            open={openModalDeleteGrado}
            onOpenChange={() => setOpenModalDeleteGrado(false)}
        >
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>Eliminar Grado Escolar</AlertDialogTitle>
                    <AlertDialogDescription>
                        ¿Estás seguro de que deseas eliminar el grado escolar "
                        {grado?.nombre}"? Esta acción no se puede deshacer.
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <footer className="flex justify-around gap-4 mt-4">
                    <Button
                        type="button"
                        onClick={() => setOpenModalDeleteGrado(false)}
                        variant="secondary"
                    >
                        Cancelar
                    </Button>
                    <Button
                        type="button"
                        onClick={handleDelete}
                        disabled={processing}
                        variant="destructive"
                    >
                        Eliminar
                    </Button>
                </footer>
            </AlertDialogContent>
        </AlertDialog>
    );
}
