import { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { AlertTriangle } from "lucide-react";
import { createNodedcAccentStyleVars, type RgbTuple } from "../lib/accentContrast";
import { Button } from "../ui/Button";

const DELETE_MODAL_ACCENT_RGB: RgbTuple = [247, 248, 244];

export interface NodeDcDeleteModalProps {
  isOpen: boolean;
  title: string;
  description: ReactNode;
  cancelLabel?: string;
  confirmLabel?: string;
  submittingLabel?: string;
  accentRgb?: RgbTuple;
  onClose: () => void;
  onConfirm: () => void | Promise<void>;
}

export function NodeDcDeleteModal({
  isOpen,
  title,
  description,
  cancelLabel = "Отмена",
  confirmLabel = "Удалить",
  submittingLabel = "Удаляем",
  accentRgb = DELETE_MODAL_ACCENT_RGB,
  onClose,
  onConfirm,
}: NodeDcDeleteModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const mountedRef = useRef(false);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  useEffect(() => {
    if (!isOpen) {
      setIsSubmitting(false);
      return;
    }

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen || typeof document === "undefined") return null;

  async function handleConfirm() {
    if (isSubmitting) return;

    setIsSubmitting(true);
    try {
      await onConfirm();
    } finally {
      if (mountedRef.current) setIsSubmitting(false);
    }
  }

  return createPortal(
    <div className="nodedc-delete-modal-layer" role="presentation" onPointerDown={onClose}>
      <article
        className="nodedc-delete-modal nodedc-glass-detail-surface"
        role="dialog"
        aria-modal="true"
        aria-labelledby="nodedc-delete-modal-title"
        style={createNodedcAccentStyleVars(accentRgb, "--nodedc-delete-accent-rgb", "--nodedc-delete-on-accent-rgb")}
        onPointerDown={(event) => event.stopPropagation()}
      >
        <div className="nodedc-delete-modal__body">
          <span className="nodedc-delete-modal__icon" aria-hidden="true">
            <AlertTriangle size={21} strokeWidth={1.9} />
          </span>
          <div className="nodedc-delete-modal__copy">
            <h3 id="nodedc-delete-modal-title">{title}</h3>
            <div className="nodedc-delete-modal__text">{description}</div>
          </div>
        </div>
        <div className="nodedc-delete-modal__foot">
          <Button variant="secondary" surface="modal" type="button" onClick={onClose} disabled={isSubmitting}>
            {cancelLabel}
          </Button>
          <Button variant="accent" surface="modal" accentRgb={accentRgb} type="button" onClick={handleConfirm} disabled={isSubmitting}>
            {isSubmitting ? submittingLabel : confirmLabel}
          </Button>
        </div>
      </article>
    </div>,
    document.body
  );
}
