import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogMedia,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils";
import { router } from "@inertiajs/react";
import { Trash, Trash2Icon } from "lucide-react"
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Spinner } from "../ui/spinner";


interface DeleteAlertDialogProps {
    deleteId: number;
    model: string;
    title: string;
    className?: string;
    variant?: "link" | "default" | "destructive" | "outline" | "secondary" | "ghost" | null | undefined
    onDeleted?: () => void; // optional callback for 
}

export function DeleteAlertButton({ deleteId, model, title, onDeleted, className, variant = 'outline' }: DeleteAlertDialogProps) {


    const [processing, setProcessing] = useState(false)

    const handleConfirm = () => {

        setProcessing(true)

        router.delete(`/dashboard/${model}/${deleteId}`, {
            onSuccess: () => {
                toast.success('Successfuly Deleted..!')
                setProcessing(false)
                if (onDeleted) onDeleted()
            },
            onError: (error) => {
                toast.error(error.message)
                setProcessing(false)
            },

            onFinish: () => {
                setProcessing(false)
            }
        })
    };


    return (
        <AlertDialog>
            <AlertDialogTrigger asChild>
                <Button disabled={processing} size="icon-sm" variant={variant} className={cn("text-destructive hover:border-destructive/10 hover:text-destructive hover:scale-105 active:scale-98 ", className)}>  {processing ? <Spinner /> : <Trash />}                </Button>
            </AlertDialogTrigger>

            <AlertDialogContent size="sm">
                <AlertDialogHeader>
                    <AlertDialogMedia className="bg-destructive/10 text-destructive dark:bg-destructive/20 dark:text-destructive">
                        <Trash2Icon />
                    </AlertDialogMedia>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                        This action cannot be undone. This will permanently delete from the database.
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction variant='destructive' type="button" onClick={handleConfirm} disabled={processing} >Delete</AlertDialogAction>
                </AlertDialogFooter>
            </AlertDialogContent>
        </AlertDialog>
    )
}
