import { useState, useRef, useEffect, useCallback } from 'react';
import { FILTER_CATEGORIES } from '../stores/filterDefs';

interface Props {
  onSelectFilter: (filterId: string) => void;
}

interface SearchResult {
  id: string;
  name: string;
  category: string;
}

export function FilterSearchBar({ onSelectFilter }: Props) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [open, setOpen] = useState(false);
  const [selectedIdx, setSelectedIdx] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);

  // Build flat list of all filters
  const allFilters = useRef<SearchResult[]>([]);
  if (allFilters.current.length === 0) {
    for (const cat of FILTER_CATEGORIES) {
      for (const f of cat.filters) {
        if (f.implemented) {
          allFilters.current.push({ id: f.id, name: f.name, category: cat.name });
        }
      }
    }
  }

  const doSearch = useCallback((q: string) => {
    if (!q.trim()) { setResults([]); return; }
    const lower = q.toLowerCase();
    const matches = allFilters.current.filter(
      f => f.name.toLowerCase().includes(lower) || f.category.toLowerCase().includes(lower)
    ).slice(0, 20);
    setResults(matches);
    setSelectedIdx(0);
  }, []);

  useEffect(() => {
    doSearch(query);
  }, [query, doSearch]);

  // Ctrl+F to focus
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        inputRef.current?.focus();
        setOpen(true);
      }
      if (e.key === 'Escape' && open) {
        setOpen(false);
        setQuery('');
        inputRef.current?.blur();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [open]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedIdx(i => Math.min(i + 1, results.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSelectedIdx(i => Math.max(i - 1, 0)); }
    else if (e.key === 'Enter' && results[selectedIdx]) {
      onSelectFilter(results[selectedIdx].id);
      setOpen(false); setQuery('');
    }
  };

  return (
    <div style={{ position: 'relative', display: 'inline-block' }} data-testid="filter-search">
      <div style={{ display: 'flex', alignItems: 'center', background: '#fff', border: '1px solid #aaa', borderRadius: 3, padding: '1px 4px' }}>
        <img src="/icons/search.png" alt="" style={{ width: 16, height: 16, opacity: 0.5, marginRight: 4 }}
          onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
        <input
          ref={inputRef}
          data-testid="filter-search-input"
          value={query}
          onChange={e => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          onKeyDown={handleKeyDown}
          placeholder="Search filters..."
          style={{
            border: 'none', outline: 'none', fontSize: 12, height: 22,
            width: open ? 260 : 160, transition: 'width 0.2s',
          }}
        />
      </div>
      {open && results.length > 0 && (
        <div style={{
          position: 'absolute', top: '100%', left: 0, right: 0,
          background: '#fff', border: '1px solid #ccc', borderRadius: 3,
          maxHeight: 300, overflowY: 'auto', zIndex: 1000, boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
        }}>
          {results.map((r, i) => (
            <div
              key={r.id}
              data-testid="search-result"
              onClick={() => { onSelectFilter(r.id); setOpen(false); setQuery(''); }}
              style={{
                padding: '4px 8px', cursor: 'pointer', fontSize: 12,
                background: i === selectedIdx ? '#d0e0ff' : 'transparent',
              }}
              onMouseEnter={() => setSelectedIdx(i)}
            >
              <div style={{ fontWeight: 500 }}>{r.name}</div>
              <div style={{ fontSize: 10, color: '#888' }}>{r.category}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
