'use client';

import {
  useEffect,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
} from 'react';
import { createPortal } from 'react-dom';
import { portalMenuStyle } from '@/features/objects/ui/Dropdown';
import { cn } from '@/lib/utils/cn';

export type CustomSelectOption = {
  value: string;
  label: string;
  /** Second line that tells apart options with the same label, e.g. an owner's email. */
  sub?: string;
  /** Closed-trigger text; defaults to label (or `label (sub)` when sub is set). */
  triggerLabel?: string;
  /** A deactivated or removed owner. */
  inactive?: boolean;
};

/** The options whose label or second line contains the search. */
export function matchingOptions(options: CustomSelectOption[], search: string) {
  const q = search.trim().toLowerCase();
  if (!q) return options;
  return options.filter((o) => `${o.label} ${o.sub ?? ''}`.toLowerCase().includes(q));
}

type CustomSelectProps = {
  id?: string;
  placeholder: string;
  value: string;
  options: CustomSelectOption[];
  onChange: (value: string) => void;
  searchable?: boolean;
  disabled?: boolean;
  className?: string;
  /** Wider dropdown for long labels. */
  menuMinWidth?: number;
  /**
   * When true, the placeholder is also listed as the first empty option.
   * Default false: placeholder shows only on the closed trigger when nothing is selected.
   * Use Clear (when a value is set) to reset.
   */
  showPlaceholderOption?: boolean;
  /** The search box's text. Default: "Search <placeholder>". */
  searchPlaceholder?: string;
  /** The line shown when nothing matches. Default: "No matches". */
  emptyText?: string;
  /** A link under the list ("Create new segment"), in place of Clear and Done. */
  footerAction?: { label: string; onSelect: () => void };
  /**
   * Clear and Done under an open list. Off for a picker that must always keep a value,
   * such as Settings › Tasks.
   */
  menuActions?: boolean;
  /**
   * Draws the open list on the body, placed against the trigger (flipped above it when there is
   * no room below), so a dialog or scrolling panel can't clip it. It closes when the page
   * scrolls or resizes. Default false: the list sits under the trigger.
   */
  portal?: boolean;
};

function ChevronIcon() {
  return (
    <svg
      className="custom-select__icon"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

/** Design-system single-select dropdown (custom-select.css). */
export function CustomSelect({
  id,
  placeholder,
  value,
  options,
  onChange,
  searchable = true,
  disabled = false,
  className = '',
  menuMinWidth = 200,
  showPlaceholderOption = false,
  searchPlaceholder,
  emptyText = 'No matches',
  footerAction,
  menuActions = true,
  portal = false,
}: CustomSelectProps) {
  const autoId = useId();
  const selectId = id ?? autoId;
  const rootRef = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<CSSProperties>();
  const [search, setSearch] = useState('');

  const selected = options.find((o) => o.value === value);
  const display = selected
    ? (selected.triggerLabel ??
      (selected.sub ? `${selected.label} (${selected.sub})` : selected.label))
    : placeholder;

  const filtered = useMemo(() => matchingOptions(options, search), [options, search]);

  // Placed once the list has a size (it changes as the search filters it); hidden until then.
  useLayoutEffect(() => {
    if (!open || !portal) return;
    const r = triggerRef.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 },
        'left',
      ),
      display: 'flex',
      width: r.width,
      minWidth: menuMinWidth,
      // Above a dialog (the modal overlays sit at 10040).
      zIndex: 100000,
    });
  }, [open, portal, filtered.length, menuMinWidth]);

  useEffect(() => {
    if (!open) {
      setSearch('');
      setPos(undefined);
      return;
    }
    const onDoc = (e: MouseEvent) => {
      const t = e.target as Node;
      if (rootRef.current?.contains(t) || menuRef.current?.contains(t)) return;
      setOpen(false);
    };
    const onMove = (e: Event) => {
      if (e.target instanceof Node && menuRef.current?.contains(e.target)) return;
      setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      // Escape closes this menu first, not the dialog or drawer around it (QA go-live: Segments 1009).
      e.stopPropagation();
      setOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey, true);
    if (portal) {
      window.addEventListener('scroll', onMove, true);
      window.addEventListener('resize', onMove);
    }
    queueMicrotask(() => searchRef.current?.focus());
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey, true);
      window.removeEventListener('scroll', onMove, true);
      window.removeEventListener('resize', onMove);
    };
  }, [open, portal]);

  const menu = (
    <div
      ref={menuRef}
      className="custom-select__dropdown"
      style={
        portal
          ? (pos ?? {
              position: 'fixed',
              top: 0,
              left: 0,
              display: 'flex',
              visibility: 'hidden',
              minWidth: menuMinWidth,
            })
          : { minWidth: menuMinWidth }
      }
      role="listbox"
      aria-label={placeholder}
    >
      {searchable ? (
        <div className="custom-select__search">
          <input
            ref={searchRef}
            type="search"
            placeholder={searchPlaceholder ?? `Search ${placeholder.toLowerCase()}`}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      ) : null}
      <ul className="custom-select__options">
        {showPlaceholderOption ? (
          <li
            className={cn('custom-select__option', !value && 'is-selected')}
            role="option"
            aria-selected={!value}
            onClick={() => {
              onChange('');
              setOpen(false);
            }}
          >
            <span className="custom-select__option-text">{placeholder}</span>
          </li>
        ) : null}
        {filtered.map((opt) => (
          <li
            key={opt.value}
            className={cn(
              'custom-select__option',
              opt.value === value && 'is-selected',
              opt.inactive && 'is-inactive',
            )}
            role="option"
            aria-selected={opt.value === value}
            aria-disabled={opt.inactive || undefined}
            onClick={() => {
              if (opt.inactive) return;
              onChange(opt.value);
              setOpen(false);
            }}
          >
            <span className="custom-select__option-text">
              {opt.label}
              {opt.sub ? <small className="custom-select__option-sub">{opt.sub}</small> : null}
            </span>
          </li>
        ))}
        {filtered.length === 0 ? (
          <li className="custom-select__option" style={{ cursor: 'default', opacity: 0.65 }}>
            <span className="custom-select__option-text">{emptyText}</span>
          </li>
        ) : null}
      </ul>
      {footerAction ? (
        <div className="lp-bx__mfoot">
          <button
            type="button"
            className="lp-link"
            onClick={() => {
              setOpen(false);
              footerAction.onSelect();
            }}
          >
            {footerAction.label}
          </button>
        </div>
      ) : menuActions && value ? (
        <div className="custom-select__actions">
          <button
            type="button"
            className="custom-select__btn custom-select__btn--clear"
            onClick={() => {
              onChange('');
              setOpen(false);
            }}
          >
            Clear
          </button>
          <button
            type="button"
            className="custom-select__btn custom-select__btn--done"
            onClick={() => setOpen(false)}
          >
            Done
          </button>
        </div>
      ) : null}
    </div>
  );

  return (
    <div
      ref={rootRef}
      id={selectId}
      className={cn('custom-select-wrapper', open && 'is-open', value && 'is-set', className)}
      data-custom-select
      data-type="single"
      data-placeholder={placeholder}
    >
      <button
        ref={triggerRef}
        type="button"
        className="custom-select__trigger"
        disabled={disabled}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={placeholder}
        onClick={() => {
          if (!disabled) setOpen((v) => !v);
        }}
      >
        <span className="custom-select__value">{display}</span>
        <ChevronIcon />
      </button>

      {open ? (portal ? createPortal(menu, document.body) : menu) : null}
    </div>
  );
}
