76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
"use client";
|
|
|
|
import { useState, type ReactNode } from "react";
|
|
import { Loader2 } from "lucide-react";
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogAction,
|
|
AlertDialogCancel,
|
|
AlertDialogContent,
|
|
AlertDialogDescription,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
AlertDialogTrigger,
|
|
} from "@/components/ui/alert-dialog";
|
|
|
|
export function ConfirmDialog({
|
|
trigger,
|
|
title,
|
|
description,
|
|
confirmLabel = "Conferma",
|
|
loadingLabel = "Attendere...",
|
|
destructive = true,
|
|
onConfirm,
|
|
}: {
|
|
trigger: ReactNode;
|
|
title: string;
|
|
description: string;
|
|
confirmLabel?: string;
|
|
loadingLabel?: string;
|
|
destructive?: boolean;
|
|
onConfirm: () => Promise<void> | void;
|
|
}) {
|
|
const [open, setOpen] = useState(false);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const handleConfirm = async () => {
|
|
setLoading(true);
|
|
try {
|
|
await onConfirm();
|
|
setOpen(false);
|
|
} catch (error) {
|
|
console.error(error);
|
|
alert("Si è verificato un errore. Riprova.");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<AlertDialog open={open} onOpenChange={setOpen}>
|
|
<AlertDialogTrigger asChild>{trigger}</AlertDialogTrigger>
|
|
<AlertDialogContent>
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>{title}</AlertDialogTitle>
|
|
<AlertDialogDescription>{description}</AlertDialogDescription>
|
|
</AlertDialogHeader>
|
|
<AlertDialogFooter>
|
|
<AlertDialogCancel disabled={loading}>Annulla</AlertDialogCancel>
|
|
<AlertDialogAction
|
|
variant={destructive ? "destructive" : "default"}
|
|
disabled={loading}
|
|
onClick={(e) => {
|
|
e.preventDefault();
|
|
handleConfirm();
|
|
}}
|
|
>
|
|
{loading && <Loader2 className="size-4 animate-spin" />}
|
|
{loading ? loadingLabel : confirmLabel}
|
|
</AlertDialogAction>
|
|
</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
);
|
|
}
|