import React, { useEffect, useId, useRef } from "react";
import { acquireAdminOverlayLock, releaseAdminOverlayLock } from "./overlayLock";
import { trapFocusWithin } from "../../shared/focusTrap";

function toModalWidth(width) {
  if (typeof width === "number" && Number.isFinite(width) && width > 0) {
    return `${width}px`;
  }
  if (typeof width === "string" && width.trim() !== "") {
    return width.trim();
  }
  return "720px";
}

export function Modal({ open, title, subtitle = "", onClose, children, footer = null, width = "720px", initialFocusRef = null }) {
  const titleId = useId();
  const panelRef = useRef(null);
  const closeRef = useRef(null);
  const restoreFocusRef = useRef(null);

  useEffect(() => {
    if (!open) return undefined;

    restoreFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    acquireAdminOverlayLock();

    const focusTarget = initialFocusRef?.current || closeRef.current || panelRef.current;
    const frame = window.requestAnimationFrame(() => {
      focusTarget?.focus?.();
    });

    const handleKeyDown = (event) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onClose?.();
        return;
      }

      trapFocusWithin(event, panelRef.current, closeRef.current);
    };

    document.addEventListener("keydown", handleKeyDown);

    return () => {
      releaseAdminOverlayLock();
      document.removeEventListener("keydown", handleKeyDown);
      window.cancelAnimationFrame(frame);
      restoreFocusRef.current?.focus?.();
    };
  }, [open, onClose, initialFocusRef]);

  if (!open) return null;

  return (
    <div className="bp-ui-modal-root">
      <div className="bp-ui-modal-backdrop" onMouseDown={onClose} aria-hidden="true" />
      <section
        ref={panelRef}
        className="bp-ui-modal-panel"
        style={{ "--bp-modal-width": toModalWidth(width) }}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
        onMouseDown={(event) => event.stopPropagation()}
      >
        <div className="bp-ui-modal-header">
          <div className="bp-ui-modal-headings">
            <div id={titleId} className="bp-ui-modal-title">{title}</div>
            {subtitle ? <div className="bp-ui-modal-subtitle">{subtitle}</div> : null}
          </div>
          <button ref={closeRef} type="button" className="bp-ui-modal-close" onClick={onClose} aria-label="Close">
            x
          </button>
        </div>
        <div className="bp-ui-modal-body">{children}</div>
        {footer ? <div className="bp-ui-modal-footer">{footer}</div> : null}
      </section>
    </div>
  );
}
