'use client';

import { useEffect, useRef, useState } from 'react';

/**
 * Pick an existing department or type a new one (LEIS-948's invite form —
 * there is no fixed list; a company builds its own). Ported from the design's
 * initCombo(): a text input with a listbox that filters as you type, arrow-key
 * navigation, and a "Create "…"" option when nothing matches exactly. The list
 * is `position: fixed` so the modal's own scroll area can't clip it.
 */
export default function DepartmentCombobox({
  id,
  value,
  onChange,
  departments,
  invalid,
}: {
  id: string;
  value: string;
  onChange: (value: string) => void;
  departments: string[];
  invalid?: boolean;
}) {
  const wrapRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [typed, setTyped] = useState(false);
  const [focusIndex, setFocusIndex] = useState(-1);
  const [placement, setPlacement] = useState<{ top?: number; bottom?: number; left: number; width: number; maxHeight: number }>({
    left: 0,
    width: 0,
    maxHeight: 240,
  });

  const raw = value.trim();
  const query = typed ? raw.toLowerCase() : '';
  const options = departments.filter((d) => !query || d.toLowerCase().includes(query));
  const exact = departments.some((d) => d.toLowerCase() === raw.toLowerCase());
  const showCreate = Boolean(raw) && !exact;

  const place = () => {
    const el = inputRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const listHeight = Math.min((listRef.current?.scrollHeight ?? 240) + 8, 240);
    const below = window.innerHeight - r.bottom - 12;
    const above = r.top - 12;
    if (below < listHeight && above > below) {
      setPlacement({ bottom: window.innerHeight - r.top + 6, left: r.left, width: r.width, maxHeight: Math.min(240, above) });
    } else {
      setPlacement({ top: r.bottom + 6, left: r.left, width: r.width, maxHeight: Math.max(120, Math.min(240, below)) });
    }
  };

  const openList = (startTyped: boolean) => {
    setTyped(startTyped);
    setFocusIndex(-1);
    setOpen(true);
  };
  const close = () => {
    setOpen(false);
    setTyped(false);
  };
  const pick = (v: string) => {
    onChange(v);
    close();
  };

  useEffect(() => {
    if (open) place();
  }, [open, options.length]);

  useEffect(() => {
    if (!open) return;
    const onScroll = () => place();
    window.addEventListener('resize', onScroll);
    document.addEventListener('scroll', onScroll, true);
    return () => {
      window.removeEventListener('resize', onScroll);
      document.removeEventListener('scroll', onScroll, true);
    };
  }, [open]);

  const allOptions = showCreate ? [...options, '__create__'] : options;

  return (
    <div ref={wrapRef} className={`wf-combo${open ? ' open' : ''}`}>
      <input
        ref={inputRef}
        type="text"
        id={id}
        className={`fra-input${invalid ? ' is-invalid' : ''}`}
        maxLength={50}
        placeholder="Select or type a department"
        autoComplete="off"
        role="combobox"
        aria-expanded={open}
        aria-controls={`${id}-list`}
        value={value}
        onChange={(e) => {
          onChange(e.target.value);
          openList(true);
        }}
        onFocus={() => openList(false)}
        onClick={() => {
          if (!open) openList(false);
        }}
        onBlur={() => {
          window.setTimeout(close, 120);
        }}
        onKeyDown={(e) => {
          if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
            e.preventDefault();
            if (!open) {
              openList(false);
              return;
            }
            if (allOptions.length === 0) return;
            setFocusIndex((i) => (i + (e.key === 'ArrowDown' ? 1 : -1) + allOptions.length) % allOptions.length);
          } else if (e.key === 'Enter' && open) {
            if (focusIndex >= 0 && allOptions[focusIndex] !== undefined) {
              e.preventDefault();
              pick(allOptions[focusIndex] === '__create__' ? raw : allOptions[focusIndex]);
            } else {
              close();
            }
          } else if (e.key === 'Escape' && open) {
            e.preventDefault();
            e.stopPropagation();
            close();
          } else if (e.key === 'Tab') {
            close();
          }
        }}
      />
      <i className="bi bi-chevron-down wf-combo-caret" aria-hidden />
      {open && (
        <div
          ref={listRef}
          id={`${id}-list`}
          className="wf-combo-list"
          role="listbox"
          style={{
            display: 'block',
            left: placement.left,
            width: placement.width,
            top: placement.top,
            bottom: placement.bottom,
            maxHeight: placement.maxHeight,
          }}
          onMouseDown={(e) => e.preventDefault()}
        >
          {options.length === 0 && !showCreate && <div className="wf-combo-empty">No departments found</div>}
          {options.map((d, i) => {
            const selected = d.toLowerCase() === raw.toLowerCase();
            return (
              <button
                key={d}
                type="button"
                role="option"
                aria-selected={selected}
                className={`${selected ? 'is-selected' : ''}${focusIndex === i ? ' is-focused' : ''}`}
                onClick={() => pick(d)}
              >
                <span>{d}</span>
                {selected && <i className="bi bi-check-lg wf-combo-check" aria-hidden />}
              </button>
            );
          })}
          {showCreate && (
            <button
              type="button"
              role="option"
              aria-selected={false}
              className={`is-new${focusIndex === options.length ? ' is-focused' : ''}`}
              onClick={() => pick(raw)}
            >
              <i className="bi bi-plus-lg" aria-hidden />
              <span>Create &quot;{raw}&quot;</span>
              <small>New department</small>
            </button>
          )}
        </div>
      )}
    </div>
  );
}
