'use client';

import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { cn } from '@/lib/utils/cn';
import { LpI, SaIcon } from './icons';

/** The design's popovers (`popOpen` / `lpMenu` / `selectPop`) and dialog (`dialog`), in React. */

function useAnchor(anchor: HTMLElement | null) {
  return useMemo(() => ({ current: anchor }), [anchor]);
}

/** `popOpen`: an `lp-pop` under the button that opened it. */
export function SaPop({
  anchor,
  onClose,
  className,
  width,
  align = 'start',
  label,
  children,
}: {
  anchor: HTMLElement | null;
  onClose: () => void;
  className?: string;
  width?: number;
  align?: 'start' | 'end';
  label?: string;
  children: ReactNode;
}) {
  const ref = useAnchor(anchor);
  return (
    <AnchoredPopover
      open={Boolean(anchor)}
      anchorRef={ref}
      onClose={onClose}
      className={cn('lp-pop is-open sa-layer', className)}
      width={width}
      fitContent={!width}
      align={align}
      design
      menu
      returnFocus
      // Over the design's dialogs (.sa-modal-ov 10070, .lp-modal-ov 10040).
      zIndex={10080}
      label={label}
    >
      <div className="lp-pop__body">{children}</div>
    </AnchoredPopover>
  );
}

export interface MenuItem {
  label: string;
  onClick?: () => void;
  href?: string;
  on?: boolean;
  disabled?: boolean;
}

/** `lpMenu`: a list of actions. */
export function MenuPop({
  anchor,
  onClose,
  items,
  align,
}: {
  anchor: HTMLElement | null;
  onClose: () => void;
  items: MenuItem[];
  align?: 'start' | 'end';
}) {
  return (
    <SaPop anchor={anchor} onClose={onClose} className="lp-pop--menu" align={align}>
      <div className="lp-menu" role="menu">
        {items.map((it) => {
          const inner = (
            <>
              <span className="lp-menu__label">{it.label}</span>
              {it.on ? (
                <span className="lp-menu__check">
                  <LpI name="check" />
                </span>
              ) : null}
            </>
          );
          const cls = cn('lp-menu__item', it.on && 'is-checked');
          return it.href ? (
            <a
              key={it.label}
              className={cls}
              role="menuitem"
              href={it.href}
              onClick={() => onClose()}
            >
              {inner}
            </a>
          ) : (
            <button
              key={it.label}
              type="button"
              className={cls}
              role="menuitem"
              disabled={it.disabled}
              onClick={() => {
                onClose();
                it.onClick?.();
              }}
            >
              {inner}
            </button>
          );
        })}
      </div>
    </SaPop>
  );
}

export interface SelectOption {
  value: string;
  label: string;
  hint?: string;
}

/** `selectPop`: a single choice, with a search box unless `search` is false. */
export function SelectPop({
  anchor,
  onClose,
  groups,
  value,
  onPick,
  search = true,
  minWidth = 200,
}: {
  anchor: HTMLElement | null;
  onClose: () => void;
  groups: { label: string; options: SelectOption[] }[];
  value: string | null;
  onPick: (value: string) => void;
  search?: boolean;
  minWidth?: number;
}) {
  const [q, setQ] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    const t = window.setTimeout(() => inputRef.current?.focus(), 30);
    return () => window.clearTimeout(t);
  }, []);
  const needle = q.trim().toLowerCase();
  const shown = groups
    .map((g) => ({
      ...g,
      options: g.options.filter((o) => !needle || o.label.toLowerCase().includes(needle)),
    }))
    .filter((g) => g.options.length);
  const width = Math.max(anchor?.offsetWidth ?? 0, minWidth);
  return (
    <SaPop
      anchor={anchor}
      onClose={onClose}
      className="lp-pop--pick sa-selpop lp-pop--pick-big"
      width={width}
    >
      <div className="lp-propdd">
        {search ? (
          <div className="lp-propdd__search">
            <label className="lp-search lp-search--sm">
              <LpI name="search" />
              <input
                ref={inputRef}
                type="search"
                placeholder="Search"
                aria-label="Search"
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
            </label>
          </div>
        ) : null}
        <div className="lp-propdd__list" role="listbox">
          {shown.length ? (
            shown.map((g) => (
              <div key={g.label || 'all'}>
                {g.label ? <div className="lp-propdd__gh">{g.label}</div> : null}
                {g.options.map((o) => (
                  <button
                    key={o.value}
                    type="button"
                    className={cn('lp-propdd__item sa-pd', o.value === value && 'is-on')}
                    role="option"
                    aria-selected={o.value === value}
                    onClick={() => {
                      onClose();
                      onPick(o.value);
                    }}
                  >
                    {o.label}
                    {o.hint ? <small>{o.hint}</small> : null}
                  </button>
                ))}
              </div>
            ))
          ) : (
            <div className="sa-pd-empty">No results</div>
          )}
        </div>
      </div>
    </SaPop>
  );
}

/**
 * `dialog`: the design's `.sa-modal`, drawn inside the page (`.sa`) so its tokens apply. Escape
 * and a click on the backdrop close it; focus goes back to what had it.
 */
export function SaDialog({
  title,
  onClose,
  className,
  children,
  footer,
}: {
  title: string;
  onClose: () => void;
  className?: string;
  children: ReactNode;
  footer?: ReactNode;
}) {
  const boxRef = useRef<HTMLDivElement>(null);
  const closeRef = useRef(onClose);
  closeRef.current = onClose;
  useEffect(() => {
    const opener = document.activeElement as HTMLElement | null;
    const t = window.setTimeout(() => {
      const box = boxRef.current;
      (
        box?.querySelector<HTMLElement>('[data-autofocus]') ??
        box?.querySelector<HTMLElement>('.sa-modal__body :is(input, select, textarea)') ??
        box?.querySelector<HTMLElement>('.sa-modal__foot .sa-btn')
      )?.focus();
    }, 0);
    const onKey = (e: KeyboardEvent) => {
      // A popover opened from the dialog closes first (it stops the event).
      if (e.key === 'Escape' && !document.querySelector('.lp-pop.sa-layer')) {
        e.stopPropagation();
        closeRef.current();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => {
      window.clearTimeout(t);
      document.removeEventListener('keydown', onKey);
      opener?.focus?.({ preventScroll: true });
    };
  }, []);
  return (
    <div
      className={cn('sa-modal-ov', className)}
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div ref={boxRef} className="sa-modal" role="dialog" aria-modal="true" aria-label={title}>
        <header className="sa-modal__head">
          <h2>{title}</h2>
          <button type="button" className="sa-x" aria-label="Close" onClick={onClose}>
            <SaIcon name="x" />
          </button>
        </header>
        <div className="sa-modal__body">{children}</div>
        {footer ? <footer className="sa-modal__foot">{footer}</footer> : null}
      </div>
    </div>
  );
}
