"use client";

import { useEffect, useId, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";

import { cx } from "@/services/travel-policy/policy-format";

/**
 * The `.bz-overlay` dialog shell, for the Travel Policy page's five modals and
 * three drawers.
 *
 * The existing `.bz-*` modals (`components/payment-cards/*`) each write this
 * markup inline, which is fine for one confirmation apiece. Eight dialogs on
 * one screen is a different proposition: the Escape key, the focus return, the
 * scroll lock and the backdrop click are the same four things every time, and
 * writing them eight times means getting them right eight times.
 *
 * Deliberately NOT `components/ui/Modal.tsx` or `components/ui/Drawer.tsx`:
 * the first renders Bootstrap's `.modal`/`.modal-dialog` structure and the
 * second is a swipe-dismissable bottom sheet. Both would need their own markup
 * replaced to carry `.bz-modal`, which is the whole point of vendoring the
 * design's stylesheet.
 *
 * Portalled to `document.body` for the reason `ui/Modal.tsx` documents: a
 * `position: fixed` backdrop rendered inside any transformed ancestor
 * positions against that ancestor instead of the viewport, leaving part of the
 * page visibly undimmed. The sticky save dock on the editor is exactly such an
 * ancestor.
 */
interface PolicyOverlayProps {
  /** Named for assistive tech; the visible title lives in `children`. */
  label: string;
  /** `drawer` slides in from the right at full height (`.bz-overlay.is-drawer`). */
  variant?: "modal" | "drawer";
  /** Max width in px for a modal. Drawers are sized by the stylesheet. */
  width?: number;
  /** Extra class on the panel, for the sizing modifiers in biz-policy-corp.css. */
  panelClassName?: string;
  onClose: () => void;
  /** Blocks Escape and the backdrop while a submit is in flight, so a dialog
   *  cannot be dismissed out from under a request that is going to land. */
  busy?: boolean;
  children: ReactNode;
}

export default function PolicyOverlay({
  label,
  variant = "modal",
  width,
  panelClassName,
  onClose,
  busy = false,
  children,
}: PolicyOverlayProps) {
  const headingId = useId();
  const panelRef = useRef<HTMLDivElement>(null);
  /** Whatever had focus when this opened, so it can be handed back on close. */
  const returnFocusRef = useRef<HTMLElement | null>(null);

  // Mounted-only portal target. Reading `document` during SSR throws, and a
  // ref is enough here — nothing needs to re-render when it becomes available
  // because the parent only renders this component on the client anyway.
  const mountedRef = useRef(false);
  useEffect(() => {
    mountedRef.current = true;
  }, []);

  useEffect(() => {
    returnFocusRef.current = document.activeElement as HTMLElement | null;

    // Scroll lock. Restored to whatever it was rather than cleared, because the
    // editor's save dock sets `bz-has-dock` on <body> and a stacked dialog
    // (Save changes opened over the editor) must not reset the outer one's lock
    // when it closes.
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    // Focus the first thing worth typing into, else the panel itself, so a
    // keyboard user lands inside the dialog rather than behind it.
    const panel = panelRef.current;
    const first = panel?.querySelector<HTMLElement>(
      '[autofocus], input:not([type="hidden"]):not([disabled]), select, textarea, button:not([disabled])'
    );
    (first ?? panel)?.focus();

    return () => {
      document.body.style.overflow = previousOverflow;
      returnFocusRef.current?.focus?.();
    };
  }, []);

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        if (busy) return;
        // Stopped so a dialog stacked over another closes only the top one.
        event.stopPropagation();
        onClose();
        return;
      }

      if (event.key !== "Tab") return;

      // Focus trap. Without it, Tab walks out of the dialog into the page
      // behind the backdrop — reachable by keyboard, invisible to the mouse.
      const panel = panelRef.current;
      if (!panel) return;
      const focusable = Array.from(
        panel.querySelectorAll<HTMLElement>(
          'a[href], button:not([disabled]), input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
        )
      ).filter((el) => el.offsetParent !== null || el === document.activeElement);
      if (focusable.length === 0) return;

      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    document.addEventListener("keydown", onKeyDown, true);
    return () => document.removeEventListener("keydown", onKeyDown, true);
  }, [busy, onClose]);

  if (typeof document === "undefined") return null;

  return createPortal(
    <div
      className={cx("bz-ui", "bz-overlay", variant === "drawer" && "is-drawer")}
      // Mousedown, not click: a click that STARTED inside the panel and ended
      // on the backdrop (a drag off the end of a text selection) would
      // otherwise dismiss the dialog and discard what was typed.
      onMouseDown={(event) => {
        if (busy) return;
        if (event.target === event.currentTarget) onClose();
      }}
    >
      <div
        ref={panelRef}
        className={cx("bz-modal", variant === "drawer" && "bz-drawer", panelClassName)}
        style={variant === "modal" && width ? { maxWidth: width } : undefined}
        role="dialog"
        aria-modal="true"
        aria-label={label}
        aria-labelledby={headingId}
        tabIndex={-1}
        onMouseDown={(event) => event.stopPropagation()}
      >
        {children}
      </div>
    </div>,
    document.body
  );
}

/**
 * The design's `modalHead`: an icon tile, a title and a sub-line.
 *
 * `tone` maps onto `.bz-icon-tile.tone-*`, which is how the mockups signal what
 * kind of decision a dialog is asking for — coral for destructive, green for a
 * save, amber for a warning.
 */
export function PolicyModalHead({
  icon,
  title,
  sub,
  tone,
}: {
  icon: string;
  title: ReactNode;
  sub?: ReactNode;
  tone?: "navy" | "coral" | "green" | "indigo" | "amber";
}) {
  return (
    <div className="bz-modal-head">
      <span className={cx("bz-icon-tile", tone && `tone-${tone}`)} aria-hidden="true">
        <i className={`bi ${icon}`} />
      </span>
      <div>
        <h3 className="bz-modal-title">{title}</h3>
        {sub ? <p className="bz-modal-sub">{sub}</p> : null}
      </div>
    </div>
  );
}

/** A drawer's header: a title, an optional sub-line and the close button. */
export function PolicyDrawerHead({
  title,
  sub,
  onClose,
}: {
  title: ReactNode;
  sub?: ReactNode;
  onClose: () => void;
}) {
  return (
    <div className="bz-modal-head">
      <div>
        <h3 className="bz-modal-title">{title}</h3>
        {sub ? <p className="bz-modal-sub">{sub}</p> : null}
      </div>
      <button type="button" className="bz-icon-btn" onClick={onClose} aria-label="Close">
        <i className="bi bi-x-lg" />
      </button>
    </div>
  );
}
