"use client";

import { Search, X } from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";

type LookupProps<T> = {
  placeholder?: string;
  onSearch: (query: string) => Promise<T[]>;
  renderResult: (item: T) => ReactNode;
  onSelect: (item: T) => void;
  minChars?: number;
};

// Generic async search-select used by the position lookup (hire wizard),
// manager/superior lookup (create position), and employee multi-select
// (reorg workbench) in later phases.
export function Lookup<T>({ placeholder = "Suchen…", onSearch, renderResult, onSelect, minChars = 2 }: LookupProps<T>) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<T[]>([]);
  const [open, setOpen] = useState(false);
  // Derived from "have we finished searching for the current query yet",
  // rather than a separate state flag flipped synchronously at the top of
  // the effect below — the effect only ever sets state from the async
  // search's own completion callback now.
  const [lastSearchedQuery, setLastSearchedQuery] = useState<string | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const tooShort = query.trim().length < minChars;
  const loading = !tooShort && lastSearchedQuery !== query.trim();

  useEffect(() => {
    if (tooShort) return;
    let cancelled = false;
    const timeout = setTimeout(() => {
      onSearch(query.trim()).then((res) => {
        if (cancelled) return;
        setResults(res);
        setOpen(true);
        setLastSearchedQuery(query.trim());
      });
    }, 200);
    return () => {
      cancelled = true;
      clearTimeout(timeout);
    };
  }, [query, minChars, onSearch, tooShort]);

  // Derived rather than reset via effect: once the query drops below
  // minChars, hide the dropdown and any stale results immediately without
  // needing a synchronous setState inside the effect above.
  const showDropdown = open && !tooShort;
  const visibleResults = tooShort ? [] : results;

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, []);

  return (
    <div ref={containerRef} className="relative">
      <div className="flex items-center gap-2 rounded border border-border bg-white px-3 py-2">
        <Search className="h-4 w-4 shrink-0 text-ink-muted" />
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={placeholder}
          className="w-full text-sm outline-none placeholder:text-ink-muted"
        />
        {query && (
          <button
            type="button"
            onClick={() => {
              setQuery("");
              setResults([]);
              setOpen(false);
            }}
            aria-label="Zurücksetzen"
          >
            <X className="h-4 w-4 text-ink-muted" />
          </button>
        )}
      </div>
      {showDropdown && (
        <div className="absolute z-20 mt-1 max-h-64 w-full overflow-y-auto rounded border border-border bg-white shadow-lg">
          {loading && <div className="px-3 py-2 text-sm text-ink-muted">Suche…</div>}
          {!loading && visibleResults.length === 0 && <div className="px-3 py-2 text-sm text-ink-muted">Keine Treffer</div>}
          {!loading &&
            visibleResults.map((item, i) => (
              <button
                key={i}
                type="button"
                onClick={() => {
                  onSelect(item);
                  setQuery("");
                  setResults([]);
                  setOpen(false);
                }}
                className="block w-full px-3 py-2 text-left text-sm hover:bg-surface"
              >
                {renderResult(item)}
              </button>
            ))}
        </div>
      )}
    </div>
  );
}
