import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { useFlashToasts, showFlash, Flash } from '@/components/use-flash-toasts';
import { destroy as deleteAlert } from '@/routes/alerts';
import { useForm } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import type { Notification as Alert } from '@/types';

interface DeleteAlertProps {
    open: boolean;
    setOpen: (value: boolean) => void;
    alert: Alert;
}

export default function DeleteAlert({ open, setOpen, alert }: DeleteAlertProps) {
    const { processing, errors, reset, delete: destroy } = useForm();

    useFlashToasts({ errors });

    const handleDelete = () => {
        destroy(deleteAlert(alert.id).url, {
            onSuccess: (page) => {
                const flash = page.props.flash as Flash;
                showFlash(flash);
                reset();
                setOpen(false);
            },
            onError: () => {},
        });
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Eliminar Alerta</DialogTitle>
                </DialogHeader>
                <div className="py-4">
                    ¿Estás seguro de que deseas eliminar la alerta <b>{alert.title}</b>?
                </div>
                <DialogFooter>
                    <DialogClose asChild>
                        <Button variant="outline" type="button">
                            Cancelar
                        </Button>
                    </DialogClose>
                    <Button
                        variant="destructive"
                        onClick={handleDelete}
                        disabled={processing}
                    >
                        {processing && (
                            <LoaderCircle className="h-4 w-4 animate-spin" />
                        )}
                        Eliminar
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
