'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
import { placePop } from '@/features/snippets/ui/mtPlace';
import { cn } from '@/lib/utils/cn';

/**
 * QA #636: where a `portal` menu sits on the viewport. As `.ev-menu` (4px under the button, from
 * its left or right edge), moved back inside the viewport and flipped above the button when
 * there is no room below (the snippets `placePop`).
 */
export function portalMenuStyle(
  button: { top: number; bottom: number; left: number; right: number; width: number },
  menu: { w: number; h: number },
  view: { vw: number; vh: number },
  align: 'left' | 'right',
): CSSProperties {
  const p = placePop(button, menu, view, {
    align: align === 'right' ? 'end' : 'start',
    arrow: false,
  });
  return { position: 'fixed', top: p.top, left: p.left, right: 'auto' };
}

/**
 * `.ev-dd`: a button with a menu or small form under it (the header menus, Sort by, the
 * pipeline picker, quick filters). A click outside or Esc closes it; `children` gets `close`.
 */
export function Dropdown({
  trigger,
  triggerClassName,
  triggerLabel,
  title,
  align = 'left',
  menuClassName,
  menuRole = 'menu',
  disabled,
  openSignal,
  portal = false,
  children,
}: {
  trigger: ReactNode;
  triggerClassName: string;
  /** aria-label of the button (icon-only buttons). */
  triggerLabel?: string;
  title?: string;
  align?: 'left' | 'right';
  menuClassName?: string;
  menuRole?: 'menu' | 'dialog';
  disabled?: boolean;
  /**
   * EV13: opens the menu each time it changes to a new number above 0 (another control opens
   * it: the event row's ⋯ › Edit association labels). None or 0: only the button opens it.
   */
  openSignal?: number;
  /**
   * QA #636: draws the menu on the body, placed against the button, so a scrolling column
   * (`.evr-left`) can't clip it. It closes when the page scrolls or resizes, as the
   * ActivitiesMoreMenu does, and Esc puts focus back on the button.
   */
  portal?: boolean;
  children: (close: () => void) => ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<CSSProperties>();
  const ref = useRef<HTMLDivElement>(null);
  const btnRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  // The value at mount isn't a request: a menu mounted again (after a save) stays shut.
  const seenSignal = useRef(openSignal);
  useEffect(() => {
    if (openSignal === seenSignal.current) return;
    seenSignal.current = openSignal;
    if (openSignal && !disabled) setOpen(true);
  }, [openSignal, disabled]);

  // Placed once the menu has a size; hidden until then.
  useLayoutEffect(() => {
    if (!open || !portal) return;
    const r = btnRef.current?.getBoundingClientRect();
    const el = menuRef.current;
    if (!r || !el) return;
    const vw = document.documentElement.clientWidth || window.innerWidth;
    setPos(
      portalMenuStyle(
        r,
        { w: el.offsetWidth, h: el.offsetHeight },
        { vw, vh: window.innerHeight },
        align,
      ),
    );
  }, [open, portal, align]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (ref.current?.contains(t) || menuRef.current?.contains(t)) return;
      setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      setOpen(false);
      if (portal) btnRef.current?.focus();
    };
    const onMove = (e: Event) => {
      if (e.target instanceof Node && menuRef.current?.contains(e.target)) return;
      setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    if (portal) {
      window.addEventListener('scroll', onMove, true);
      window.addEventListener('resize', onMove);
    }
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('scroll', onMove, true);
      window.removeEventListener('resize', onMove);
    };
  }, [open, portal]);

  const menu = open ? (
    <div
      ref={menuRef}
      className={cn('ev-menu', align === 'right' && 'ev-menu--right', menuClassName)}
      role={menuRole}
      style={
        portal
          ? (pos ?? { position: 'fixed', top: 0, left: 0, right: 'auto', visibility: 'hidden' })
          : undefined
      }
    >
      {children(() => setOpen(false))}
    </div>
  ) : null;

  return (
    <div className="ev-dd" ref={ref}>
      <button
        ref={btnRef}
        type="button"
        className={cn(triggerClassName, open && 'is-open')}
        aria-haspopup={menuRole === 'menu' ? 'menu' : 'dialog'}
        aria-expanded={open}
        aria-label={triggerLabel}
        title={title}
        disabled={disabled}
        onClick={() => {
          if (!open) setPos(undefined);
          setOpen((v) => !v);
        }}
      >
        {trigger}
      </button>
      {portal && menu ? createPortal(menu, document.body) : menu}
    </div>
  );
}
