"use client";

import { memo, useMemo } from "react";
import { Loader2 } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";

interface DeleteConfirmModalProps {
  record: { ticker?: string; isin?: string; uid?: string; id?: string };
  recordName?: string;
  onCancel: () => void;
  onConfirm: () => void;
  deleteLoading: boolean;
}

/**
 * Destructive confirmation, built on shadcn `AlertDialog`.
 *
 * `AlertDialog` rather than `Dialog` is the correct primitive here: it uses
 * `role="alertdialog"`, focuses the cancel action first, and — importantly for
 * a delete — does not dismiss on an outside click or Escape, so a stray click
 * beside the dialog cannot silently abandon the decision.
 */
const DeleteConfirmModalComponent = ({
  record,
  recordName,
  onCancel,
  onConfirm,
  deleteLoading,
}: DeleteConfirmModalProps) => {
  const displayName = useMemo(() => {
    if (recordName) return recordName;
    return record.ticker || record.isin || record.uid || record.id || "this record";
  }, [record, recordName]);

  return (
    <AlertDialog open onOpenChange={(open) => !open && onCancel()}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete “{displayName}”?</AlertDialogTitle>
          <AlertDialogDescription>
            This permanently removes the record and cannot be undone. Any reports
            that include it will change once it is deleted.
          </AlertDialogDescription>
        </AlertDialogHeader>

        <AlertDialogFooter>
          <AlertDialogCancel disabled={deleteLoading}>Cancel</AlertDialogCancel>
          <AlertDialogAction
            disabled={deleteLoading}
            aria-busy={deleteLoading}
            // Keep the dialog mounted while the request is in flight; Radix
            // would otherwise close it the moment the action is pressed and
            // the user would lose the pending state.
            onClick={(event) => {
              event.preventDefault();
              onConfirm();
            }}
            className={cn(buttonVariants({ variant: "destructive" }))}
          >
            {deleteLoading && <Loader2 className="size-4 animate-spin" aria-hidden />}
            {deleteLoading ? "Deleting…" : "Delete record"}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};

export const DeleteConfirmModal = memo(DeleteConfirmModalComponent);

DeleteConfirmModal.displayName = "DeleteConfirmModal";
