'use client';

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

/**
 * The design's `.dropdown` (dropdown.css): a toggle and a `.dropdown__menu` under it, closed by a
 * click outside or Escape. `align="left"` opens it from the toggle's left edge. `fixed` places
 * the menu on the viewport (under the toggle) so a scrolling container, like a table, cannot clip
 * it; it closes when the page scrolls.
 */
export function Dropdown({
  toggle,
  toggleClassName,
  toggleLabel,
  menuClassName,
  align = 'right',
  fixed = false,
  className,
  disabled = false,
  disabledReason,
  children,
}: {
  toggle: React.ReactNode;
  toggleClassName?: string;
  /** The toggle can't be pressed (a menu that was open closes). */
  disabled?: boolean;
  /** Why it is disabled (tooltip). */
  disabledReason?: string;
  /** aria-label for an icon-only toggle. */
  toggleLabel?: string;
  menuClassName?: string;
  align?: 'left' | 'right';
  fixed?: boolean;
  className?: string;
  /** The menu; a function gets `close` to call after a pick. */
  children: React.ReactNode | ((close: () => void) => React.ReactNode);
}) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<React.CSSProperties | undefined>(undefined);
  const root = useRef<HTMLDivElement>(null);
  const button = useRef<HTMLButtonElement>(null);

  const toggleOpen = () => {
    if (!open && fixed && button.current) {
      const r = button.current.getBoundingClientRect();
      setPos(
        align === 'left'
          ? { position: 'fixed', top: r.bottom + 6, left: r.left, right: 'auto' }
          : {
              position: 'fixed',
              top: r.bottom + 6,
              right: window.innerWidth - r.right,
              left: 'auto',
            },
      );
    }
    setOpen((v) => !v);
  };

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

  const close = () => setOpen(false);

  return (
    <div className={cn('dropdown', className)} ref={root}>
      <button
        ref={button}
        type="button"
        className={toggleClassName}
        aria-expanded={open}
        aria-haspopup="menu"
        aria-label={toggleLabel}
        onClick={toggleOpen}
        disabled={disabled}
        title={disabled ? disabledReason : undefined}
      >
        {toggle}
      </button>
      {open && !disabled ? (
        <div
          className={cn('dropdown__menu', align === 'left' && 'wf-menu--left', menuClassName)}
          role="menu"
          style={fixed ? pos : undefined}
        >
          {typeof children === 'function' ? children(close) : children}
        </div>
      ) : null}
    </div>
  );
}

export function Chevron({ size = 14 }: { size?: number }) {
  return (
    <svg
      className="icon"
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

/**
 * A filter of the Workflows tab (design `.wf-filter`): a plain-text toggle with the number picked,
 * and a menu with a search box, checkboxes and Clear.
 */
export function FilterDropdown({
  label,
  options,
  value,
  onChange,
  emptyText = 'No matches',
}: {
  label: string;
  options: { value: string; label: string }[];
  /** Shown when there is nothing to pick. */
  emptyText?: string;
  value: string[];
  onChange: (next: string[]) => void;
}) {
  const [q, setQ] = useState('');
  const needle = q.trim().toLowerCase();
  const shown = options.filter((o) => !needle || o.label.toLowerCase().includes(needle));
  const toggle = (v: string) =>
    onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v]);

  return (
    <Dropdown
      className="wf-filter"
      align="left"
      toggleClassName={cn('wf-filter__btn', value.length > 0 && 'is-active')}
      menuClassName="wf-filter__menu"
      toggle={
        <>
          <span>{label}</span>
          {value.length > 0 ? <span className="wf-filter__count">{value.length}</span> : null}
          <Chevron size={12} />
        </>
      }
    >
      <div className="wf-filter__search">
        <input
          className="input"
          type="search"
          placeholder="Search"
          aria-label={`Search ${label}`}
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
      </div>
      <div className="wf-filter__opts">
        {shown.length === 0 ? (
          <p className="wf-filter__none">{options.length === 0 ? emptyText : 'No matches'}</p>
        ) : null}
        {shown.map((o) => (
          <label key={o.value} className="wf-filter__opt">
            <span className="check">
              <input
                type="checkbox"
                checked={value.includes(o.value)}
                onChange={() => toggle(o.value)}
              />
              <span className="check__box" aria-hidden />
            </span>
            <span>{o.label}</span>
          </label>
        ))}
      </div>
      <div className="wf-filter__foot">
        <button type="button" className="btn-text" onClick={() => onChange([])}>
          Clear
        </button>
      </div>
    </Dropdown>
  );
}
