import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";

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

export function DeleteObjectDialog({ id }: { id: string }) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const del = useDeleteObject();
  const [open, setOpen] = useState(false);
  const [error, setError] = useState(false);

  const onConfirm = async () => {
    setError(false);
    try {
      await del.mutateAsync(id);
    } catch {
      // Keep the dialog open so the user can retry or cancel; never let the
      // rejected mutation escape as an unhandled promise rejection.
      setError(true);
      return;
    }
    navigate("/objects");
  };

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger
        render={
          <Button variant="ghost" size="sm" className="text-destructive">
            {t("actions.delete")}
          </Button>
        }
      />

      <AlertDialogContent>
        <AlertDialogTitle>{t("actions.delete")}</AlertDialogTitle>
        <AlertDialogDescription>{t("actions.confirmDelete")}</AlertDialogDescription>
        {error && (
          <p role="alert" className="text-sm text-destructive">
            {t("form.rejected")}
          </p>
        )}
        <AlertDialogFooter>
          <AlertDialogCancel>{t("form.cancel")}</AlertDialogCancel>
          <AlertDialogAction onClick={onConfirm}>
            {t("actions.delete")}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
