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

export function ModalDeleteVideo() {
    const { video, openModalDeleteVideo, setOpenModalDeleteVideo } =
        useVideoStore();
    const { delete: destroy, processing } = useForm();

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

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

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