"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface ConfirmDeleteOptions {
  title?: string;
  description?: string;
}

export function useConfirmDelete(
  onConfirm: (id: string) => void | Promise<unknown>,
  options?: ConfirmDeleteOptions
) {
  const [targetId, setTargetId] = useState<string | null>(null);
  const [targetName, setTargetName] = useState<string>("");
  const [pending, setPending] = useState(false);

  const open = (id: string, name?: string) => {
    setTargetId(id);
    setTargetName(name ?? "this item");
  };

  const close = () => setTargetId(null);

  const Dialog = () => (
    <AlertDialog
      open={!!targetId}
      onOpenChange={(v) => !v && !pending && close()}
    >
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{options?.title ?? "Confirm Delete"}</AlertDialogTitle>
          <AlertDialogDescription>
            {options?.description ?? (
              <>
                Are you sure you want to delete <strong>{targetName}</strong>? This action cannot be undone.
              </>
            )}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel onClick={close} disabled={pending}>
            Cancel
          </AlertDialogCancel>
          <AlertDialogAction
          className="bg-destructive hover:bg-destructive/90 text-destructive-foreground min-w-[110px] justify-center"
          disabled={pending}
          onClick={async (e) => {
            e.preventDefault();
            if (!targetId || pending) return;
            setPending(true);
            try {
              await onConfirm(targetId);
              close();
            } catch {
              // error toast is handled by the mutation hook
            } finally {
              setPending(false);
            }
          }}
        >
          {pending ? (
            <span className="flex items-center gap-2">
              <Loader2 className="h-4 w-4 animate-spin" /> Deleting...
            </span>
          ) : (
            "Delete"
          )}
        </AlertDialogAction>

        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );

  return { open, Dialog };
}
