import { useEffect, useRef, useState, type ReactNode } from "react";
import { Button } from "./Button.js";
import { Window, WindowFooterActions } from "./Window.js";

export interface ConfirmationModalProps {
  open: boolean;
  title: string;
  description: ReactNode;
  confirmLabel?: string;
  cancelLabel?: string;
  pendingLabel?: string;
  danger?: boolean;
  onClose: () => void;
  onConfirm: () => void | Promise<void>;
}

export function ConfirmationModal({
  open,
  title,
  description,
  confirmLabel = "Подтвердить",
  cancelLabel = "Отмена",
  pendingLabel = "Выполняется",
  danger = false,
  onClose,
  onConfirm,
}: ConfirmationModalProps) {
  const [pending, setPending] = useState(false);
  const mounted = useRef(true);

  useEffect(() => () => {
    mounted.current = false;
  }, []);

  useEffect(() => {
    if (!open) setPending(false);
  }, [open]);

  const handleConfirm = async () => {
    if (pending) return;
    setPending(true);
    try {
      await onConfirm();
    } finally {
      if (mounted.current) setPending(false);
    }
  };

  return (
    <Window
      open={open}
      title={title}
      size="sm"
      closeOnBackdrop={!pending}
      closeOnEscape={!pending}
      onClose={onClose}
      footer={
        <>
          <span />
          <WindowFooterActions>
            <Button disabled={pending} onClick={onClose}>{cancelLabel}</Button>
            <Button variant={danger ? "danger" : "primary"} disabled={pending} onClick={handleConfirm}>
              {pending ? pendingLabel : confirmLabel}
            </Button>
          </WindowFooterActions>
        </>
      }
    >
      <div className="nodedc-confirmation">
        <span className="nodedc-confirmation__icon" aria-hidden="true">!</span>
        <div className="nodedc-confirmation__copy">{description}</div>
      </div>
    </Window>
  );
}
