import { useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTickers } from '../../hooks/useTickers';
import { Input } from '../ui/Field';

const MAX_RESULTS = 8;

/** Jump-to-ticker search over the tracked universe. Selecting a match opens its
 *  detail page — it does NOT add the ticker to the watchlist. */
export default function TickerSearch({ onNavigate }: { onNavigate?: () => void }) {
  const tickers = useTickers();
  const navigate = useNavigate();
  const [q, setQ] = useState('');
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const blurTimer = useRef<number | null>(null);

  const matches = useMemo(() => {
    const query = q.trim().toUpperCase();
    if (!query) return [];
    const all = tickers.data ?? [];
    const starts = all.filter((t) => t.symbol.toUpperCase().startsWith(query));
    const contains = all.filter(
      (t) => !t.symbol.toUpperCase().startsWith(query) && t.symbol.toUpperCase().includes(query),
    );
    return [...starts, ...contains].slice(0, MAX_RESULTS);
  }, [q, tickers.data]);

  const go = (symbol: string) => {
    navigate(`/ticker/${symbol}`);
    setQ('');
    setOpen(false);
    setActive(0);
    onNavigate?.();
  };

  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActive((a) => Math.min(a + 1, matches.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActive((a) => Math.max(a - 1, 0));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      const m = matches[active];
      if (m) go(m.symbol);
    } else if (e.key === 'Escape') {
      setQ('');
      setOpen(false);
    }
  };

  const showList = open && q.trim().length > 0 && matches.length > 0;

  return (
    <div className="relative">
      <Input
        type="text"
        value={q}
        onChange={(e) => {
          setQ(e.target.value);
          setOpen(true);
          setActive(0);
        }}
        onFocus={() => setOpen(true)}
        onBlur={() => {
          blurTimer.current = window.setTimeout(() => setOpen(false), 120);
        }}
        onKeyDown={onKeyDown}
        placeholder="Search ticker…"
        aria-label="Search ticker"
        autoComplete="off"
        className="w-full"
      />
      {showList && (
        <ul className="absolute z-20 mt-1 max-h-72 w-full overflow-y-auto rounded-lg glass py-1 shadow-xl">
          {matches.map((t, i) => (
            <li key={t.symbol}>
              <button
                type="button"
                onMouseEnter={() => setActive(i)}
                onClick={() => go(t.symbol)}
                className={`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-sm transition-colors ${
                  i === active ? 'bg-blue-400/[0.12] text-blue-200' : 'text-gray-300 hover:bg-white/[0.04]'
                }`}
              >
                <span className="font-medium">{t.symbol}</span>
                {t.name && <span className="truncate text-xs text-gray-500">{t.name}</span>}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
