"use client";

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
  type RefObject,
} from "react";
import { createPortal } from "react-dom";
import { CheckIcon, ChevronDownIcon, MagnifyingGlassIcon } from "./icons";
import {
  clampPopoverLeft,
  popoverHBounds,
  popoverWidth,
} from "./popover-position";
import { popoverZIndex, useSurfaceZIndex } from "./surface-z-index";

// The portal's settings popover, in one vocabulary: a white rounded panel under
// its trigger (right edges aligned), a title row with a red-orange text action,
// sections under small uppercase headings split by a rule, list rows, and a
// muted footnote. Built for the tables' "Columns" menu and shared by the search
// card's "Filters" menu so both read as the same kind of thing.
//
// The panel is portaled with `position: fixed` (like ActionMenu), so a toolbar
// inside a clipping container cannot crop it.

/** The default panel width, in px. */
export const MENU_PANEL_WIDTH = 288;

/** The panel's chrome: surface, radius, border, padding, shadow, scrolling. */
export const MENU_PANEL =
  "overflow-y-auto rounded-2xl border border-surface-stroke bg-surface-base p-3 shadow-floating [&::-webkit-scrollbar-track]:my-3";

type Placement = { left: number; width: number; top: number; maxHeight: number };

/**
 * A popover panel under `triggerRef`, its right edge on the trigger's.
 *
 * @remarks
 * The caller owns `open` and its trigger. A press outside the panel and the
 * trigger, or Escape, calls `onClose`; Escape also puts the focus back on the
 * trigger. The panel follows the trigger while the page scrolls or resizes.
 *
 * @param label - The dialog's accessible name (usually the title row's text).
 */
export function MenuPopover({
  open,
  onClose,
  triggerRef,
  label,
  width = MENU_PANEL_WIDTH,
  children,
}: {
  open: boolean;
  onClose: () => void;
  triggerRef: RefObject<HTMLElement | null>;
  label: string;
  width?: number;
  children: ReactNode;
}) {
  const panelRef = useRef<HTMLDivElement>(null);
  const [placement, setPlacement] = useState<Placement | null>(null);
  const surfaceZ = useSurfaceZIndex();
  const onCloseRef = useRef(onClose);
  useEffect(() => {
    onCloseRef.current = onClose;
  });

  useEffect(() => {
    if (!open) return;
    function onPointerDown(e: MouseEvent) {
      const target = e.target as Node;
      if (triggerRef.current?.contains(target)) return;
      if (panelRef.current?.contains(target)) return;
      onCloseRef.current();
    }
    // Capture phase + stop: Escape closes the menu only, not the drawer or
    // dialog the menu sits in (they listen on the document too).
    function onKeyDown(e: KeyboardEvent) {
      if (e.key !== "Escape") return;
      e.preventDefault();
      e.stopPropagation();
      onCloseRef.current();
      triggerRef.current?.focus();
    }
    document.addEventListener("mousedown", onPointerDown);
    window.addEventListener("keydown", onKeyDown, true);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      window.removeEventListener("keydown", onKeyDown, true);
    };
  }, [open, triggerRef]);

  /* eslint-disable react-hooks/set-state-in-effect -- derives fixed coords from
     the trigger's DOM rect; not a render-derived value. */
  useLayoutEffect(() => {
    if (!open) {
      setPlacement(null);
      return;
    }
    function place() {
      const button = triggerRef.current;
      if (!button) return;
      const rect = button.getBoundingClientRect();
      const margin = 8;
      const bounds = popoverHBounds(button);
      const panelWidth = popoverWidth(width, bounds, margin);
      setPlacement({
        left: clampPopoverLeft(rect.right - panelWidth, panelWidth, bounds, margin),
        width: panelWidth,
        top: rect.bottom + 8,
        maxHeight: window.innerHeight - rect.bottom - 8 - margin,
      });
    }
    place();
    window.addEventListener("scroll", place, true);
    window.addEventListener("resize", place);
    return () => {
      window.removeEventListener("scroll", place, true);
      window.removeEventListener("resize", place);
    };
  }, [open, triggerRef, width]);
  /* eslint-enable react-hooks/set-state-in-effect */

  if (!open || !placement) return null;
  return createPortal(
    <div
      ref={panelRef}
      role="dialog"
      aria-label={label}
      style={{
        position: "fixed",
        left: placement.left,
        top: placement.top,
        width: placement.width,
        maxHeight: placement.maxHeight,
        zIndex: popoverZIndex(surfaceZ),
      }}
      className={MENU_PANEL}
    >
      {children}
    </div>,
    document.body,
  );
}

/**
 * The panel's title row: the title, and on the right an optional red-orange
 * text action ("Reset", "Clear").
 *
 * @param sticky - keep the row (and its action) in view while a long panel
 *   scrolls. It paints its host's surface (`bg-inherit`), so its parent must
 *   carry the background, and assumes the host's 12 px top padding.
 */
export function MenuPanelHeader({
  title,
  action,
  sticky = false,
}: {
  title: string;
  action?: ReactNode;
  sticky?: boolean;
}) {
  return (
    <div
      className={`flex items-center justify-between gap-3 px-1 pb-2.5 ${
        sticky ? "sticky top-0 z-10 -mt-3 bg-inherit pt-3" : ""
      }`}
    >
      <span className="body-prominent text-foreground-default">{title}</span>
      {action}
    </div>
  );
}

/** The title row's text action, in the red-orange link look. */
export function MenuPanelAction({
  onClick,
  disabled = false,
  children,
}: {
  onClick: () => void;
  disabled?: boolean;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      className="clickable-small text-foreground-red-orange transition-opacity hover:underline disabled:cursor-default disabled:opacity-40 disabled:hover:no-underline"
    >
      {children}
    </button>
  );
}

/**
 * A section of the panel: a rule, a small uppercase heading, then its rows
 * (`<li>` children).
 */
export function MenuPanelSection({
  label,
  children,
}: {
  label: string;
  children: ReactNode;
}) {
  return (
    <div role="group" aria-label={label}>
      <p className="stat-small mt-1.5 border-t border-surface-stroke px-1.5 pb-1 pt-2.5 uppercase text-foreground-muted">
        {label}
      </p>
      <ul>{children}</ul>
    </div>
  );
}

/** A muted note at the foot of the panel, under a rule. */
export function MenuPanelFootnote({ children }: { children: ReactNode }) {
  return (
    <p className="body-small mt-1.5 border-t border-surface-stroke px-1.5 pt-2.5 text-foreground-muted">
      {children}
    </p>
  );
}

/**
 * A row that toggles: optional leading mark (a tag's colour dot), the label,
 * and a trailing check while it's on. The whole row is the button.
 *
 * @param label - already-localized (or an entity name).
 */
export function MenuCheckRow({
  label,
  checked,
  onToggle,
  leading,
}: {
  label: string;
  checked: boolean;
  onToggle: () => void;
  leading?: ReactNode;
}) {
  return (
    <li>
      <button
        type="button"
        aria-pressed={checked}
        onClick={onToggle}
        className="flex min-h-10 w-full items-center gap-2.5 rounded-lg px-1.5 text-left transition-colors hover:bg-surface-base-muted"
      >
        {leading}
        <span className="body-normal min-w-0 flex-1 truncate text-foreground-default">
          {label}
        </span>
        <span
          aria-hidden
          className="flex size-6 shrink-0 items-center justify-center text-foreground-default"
        >
          {checked ? <CheckIcon className="size-[18px]" /> : null}
        </span>
      </button>
    </li>
  );
}

/** A row that opens more rows in place ("Show all tags"): label and a chevron. */
export function MenuExpandRow({
  label,
  onClick,
}: {
  label: string;
  onClick: () => void;
}) {
  return (
    <li>
      <button
        type="button"
        onClick={onClick}
        aria-expanded={false}
        className="flex min-h-10 w-full items-center gap-2.5 rounded-lg px-1.5 text-left text-foreground-muted transition-colors hover:bg-surface-base-muted hover:text-foreground-default"
      >
        <span className="body-normal min-w-0 flex-1 truncate">{label}</span>
        <span aria-hidden className="flex size-6 shrink-0 items-center justify-center">
          <ChevronDownIcon className="size-4" />
        </span>
      </button>
    </li>
  );
}

/**
 * A compact search field as the first row of a section, narrowing the rows
 * under it.
 *
 * @param label - already-localized; the placeholder and the accessible name.
 */
export function MenuSearchField({
  value,
  onChange,
  label,
}: {
  value: string;
  onChange: (value: string) => void;
  label: string;
}) {
  return (
    <li className="px-1.5 pb-1 pt-0.5">
      <label className="flex items-center gap-2 rounded-lg border border-surface-stroke px-2.5 py-1.5 focus-within:border-foreground-muted">
        <MagnifyingGlassIcon className="size-4 shrink-0 text-foreground-muted" />
        <input
          type="text"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={label}
          aria-label={label}
          className="body-normal min-w-0 flex-1 bg-transparent text-foreground-default outline-none placeholder:text-foreground-muted"
        />
      </label>
    </li>
  );
}

/** A muted line in place of rows (nothing matches the section's search). */
export function MenuEmptyRow({ children }: { children: ReactNode }) {
  return <li className="body-small px-1.5 py-2.5 text-foreground-muted">{children}</li>;
}
