import { useState } from "react";
import { useTranslation } from "react-i18next";

import { errorMessageKey } from "../api/error-message";
import {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogContent,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";

export function DeleteConfirmDialog({
  description,
  onConfirm,
  triggerLabel,
}: {
  /** Confirmation prompt, e.g. t("actions.confirmDeleteTerm"). */
  description: string;
  /** Performs the delete; may throw InUseError to surface the in-use count. */
  onConfirm: () => Promise<void>;
  /** Optional override for the trigger button text (defaults to actions.delete). */
  triggerLabel?: string;
}) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  const confirm = async () => {
    setMessage(null);
    try {
      await onConfirm();
    } catch (err) {
      // Keep the dialog open; show the blocking reason. Never let the rejected
      // mutation escape as an unhandled rejection.
      const { key, opts } = errorMessageKey(err);
      setMessage(t(key, opts));
      return;
    }
    setOpen(false);
  };

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger
        render={
          <Button variant="ghost" size="sm" className="text-destructive">
            {triggerLabel ?? t("actions.delete")}
          </Button>
        }
      />
      <AlertDialogContent>
        <AlertDialogTitle>{t("actions.delete")}</AlertDialogTitle>
        <AlertDialogDescription>{description}</AlertDialogDescription>
        {message && (
          <p role="alert" className="text-sm text-destructive">
            {message}
          </p>
        )}
        <AlertDialogFooter>
          <AlertDialogCancel>{t("form.cancel")}</AlertDialogCancel>
          <AlertDialogAction onClick={confirm}>{t("actions.delete")}</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
