'use client';

import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { cn } from '@/lib/utils/cn';

export interface DropMenuItem {
  key: string;
  label: ReactNode;
  onSelect: () => void;
  disabled?: boolean;
  /** Tooltip, e.g. why the item is disabled. */
  title?: string;
  /** The current choice of a filter menu. */
  active?: boolean;
  /** Drawn after a divider. */
  separated?: boolean;
}

export function ChevronDown({ size = 14 }: { size?: number }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden>
      <path d="m7 10 5 5 5-5" fill="none" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}

/** Space kept between the menu and the window's edges. */
const EDGE = 8;

/**
 * A button and its plain text menu (sequences design: Actions, Create sequence ▾, Owner: Any,
 * row Actions). The menu is fixed-positioned so the scrolling table does not clip it. It opens
 * above the button when there is no room below, stays inside the window, and follows the
 * button when the page scrolls (QA 16 Oct #108); it closes on an outside click, Esc, resize, or
 * when the button scrolls out of view.
 */
export function DropMenu({
  trigger,
  triggerClassName,
  ariaLabel,
  items,
  align = 'end',
  disabled = false,
  searchable = false,
}: {
  trigger: ReactNode;
  triggerClassName: string;
  ariaLabel?: string;
  items: DropMenuItem[];
  /** Which trigger edge the menu lines up with. */
  align?: 'start' | 'end';
  disabled?: boolean;
  /** A search box above the items (text labels), for long lists such as owners. */
  searchable?: boolean;
}) {
  const [pos, setPos] = useState<{ top: number; left?: number; right?: number } | null>(null);
  const [term, setTerm] = useState('');
  const triggerRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const open = pos !== null;

  /** Where the menu goes for the button's place now; null when the button is out of view. */
  const place = (): { top: number; left?: number; right?: number } | null => {
    const rect = triggerRef.current?.getBoundingClientRect();
    if (!rect || rect.bottom < 0 || rect.top > window.innerHeight) return null;
    const height = menuRef.current?.offsetHeight ?? 0;
    const below = rect.bottom + 6;
    const fitsBelow = below + height <= window.innerHeight - EDGE;
    const above = rect.top - 6 - height;
    const top =
      fitsBelow || above < EDGE
        ? Math.max(EDGE, Math.min(below, window.innerHeight - EDGE - height))
        : above;
    return align === 'end'
      ? { top, right: Math.max(EDGE, window.innerWidth - rect.right) }
      : { top, left: Math.max(EDGE, Math.min(rect.left, window.innerWidth - EDGE - 190)) };
  };

  const toggle = () => {
    setTerm('');
    setPos(open ? null : place());
  };
  const needle = term.trim().toLowerCase();
  const shown = needle
    ? items.filter(
        (item) => typeof item.label === 'string' && item.label.toLowerCase().includes(needle),
      )
    : items;

  // Once the menu is drawn its height is known: move it up when it doesn't fit below.
  useLayoutEffect(() => {
    if (!open) return;
    const next = place();
    if (next && next.top !== pos?.top) setPos(next);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const close = () => setPos(null);
    const onDown = (e: MouseEvent) => {
      const target = e.target as Node;
      if (menuRef.current?.contains(target) || triggerRef.current?.contains(target)) return;
      close();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      close();
      triggerRef.current?.focus();
    };
    const onScroll = (e: Event) => {
      if (e.target instanceof Node && menuRef.current?.contains(e.target)) return;
      setPos(place());
    };
    document.addEventListener('mousedown', onDown);
    window.addEventListener('keydown', onKey);
    window.addEventListener('resize', close);
    window.addEventListener('scroll', onScroll, true);
    return () => {
      document.removeEventListener('mousedown', onDown);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', close);
      window.removeEventListener('scroll', onScroll, true);
    };
    // `place` reads refs and the fixed `align` only: the listeners need not change with it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  return (
    <>
      <button
        ref={triggerRef}
        type="button"
        className={triggerClassName}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={ariaLabel}
        disabled={disabled}
        onClick={toggle}
      >
        {trigger}
      </button>
      {pos ? (
        <div
          ref={menuRef}
          className="seqm-menu"
          role="menu"
          style={{ top: pos.top, left: pos.left, right: pos.right }}
        >
          {searchable ? (
            <input
              type="search"
              className="input seqm-menu__search"
              placeholder="Search"
              aria-label="Search"
              value={term}
              autoFocus
              onChange={(e) => setTerm(e.target.value)}
            />
          ) : null}
          {searchable && shown.length === 0 ? (
            <p className="seqm-menu__hint crm-mb-0 crm-p-2">No matches</p>
          ) : null}
          {shown.map((item) => (
            <div key={item.key}>
              {item.separated ? <div className="seqm-menu__divider" role="separator" /> : null}
              <button
                type="button"
                role="menuitem"
                className={cn('seqm-menu__item', item.active && 'is-active')}
                disabled={item.disabled}
                title={item.title}
                onClick={() => {
                  setPos(null);
                  // Sequences QA steps BUG-08: focus goes back to the menu button (the item is
                  // removed), so a dialog the item opens gives focus back to it when it closes.
                  triggerRef.current?.focus();
                  item.onSelect();
                }}
              >
                {item.label}
              </button>
            </div>
          ))}
        </div>
      ) : null}
    </>
  );
}

/** "2 days ago", "a month ago" (design: Date Modified). */
export function timeAgo(iso: string, now: number = Date.now()): string {
  const then = new Date(iso).getTime();
  if (Number.isNaN(then)) return '-';
  const seconds = Math.max(0, (now - then) / 1000);
  const minutes = seconds / 60;
  const hours = minutes / 60;
  const days = hours / 24;
  if (seconds < 45) return 'a few seconds ago';
  if (seconds < 90) return 'a minute ago';
  if (minutes < 45) return `${Math.round(minutes)} minutes ago`;
  if (minutes < 90) return 'an hour ago';
  if (hours < 22) return `${Math.round(hours)} hours ago`;
  if (hours < 36) return 'a day ago';
  if (days < 7) return `${Math.round(days)} days ago`;
  if (days < 26) {
    const weeks = Math.round(days / 7);
    return weeks === 1 ? 'a week ago' : `${weeks} weeks ago`;
  }
  if (days < 45) return 'a month ago';
  if (days < 320) return `${Math.round(days / 30.44)} months ago`;
  if (days < 548) return 'a year ago';
  return `${Math.round(days / 365.25)} years ago`;
}
