import { useState, useRef, useEffect } from 'react';
import { api, SearchResult } from '../api';

interface Props {
  onSelect: (path: string) => void;
}

export function SearchBar({ onSelect }: Props) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const timerRef = useRef<ReturnType<typeof setTimeout>>();
  const containerRef = useRef<HTMLDivElement>(null);

  // 防抖搜索
  useEffect(() => {
    if (!query.trim()) {
      setResults([]);
      setOpen(false);
      return;
    }

    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(async () => {
      setLoading(true);
      try {
        const r = await api.search(query);
        setResults(r);
        setOpen(true);
      } catch {
        setResults([]);
      } finally {
        setLoading(false);
      }
    }, 300);

    return () => clearTimeout(timerRef.current);
  }, [query]);

  // 点击外部关闭
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  return (
    <div className="kb-search" ref={containerRef}>
      <div className="kb-search-input-wrap">
        <span className="kb-search-icon">🔍</span>
        <input
          className="kb-search-input"
          type="text"
          value={query}
          onChange={e => setQuery(e.target.value)}
          placeholder="搜索文档..."
          onFocus={() => results.length > 0 && setOpen(true)}
        />
        {query && (
          <button className="kb-search-clear" onClick={() => { setQuery(''); setResults([]); setOpen(false); }}>
            ✕
          </button>
        )}
        {loading && <span className="kb-search-loading">...</span>}
      </div>

      {open && results.length > 0 && (
        <div className="kb-search-dropdown">
          {results.map((r, i) => (
            <div
              key={`${r.path}-${i}`}
              className="kb-search-result"
              onClick={() => {
                onSelect(r.path);
                setOpen(false);
                setQuery('');
              }}
            >
              <div className="kb-search-result-title">{r.title}</div>
              <div className="kb-search-result-path">{r.path}</div>
              <div className="kb-search-result-snippet">{r.snippet}</div>
            </div>
          ))}
        </div>
      )}

      {open && results.length === 0 && !loading && query && (
        <div className="kb-search-dropdown">
          <div className="kb-search-empty">没有匹配的文档</div>
        </div>
      )}
    </div>
  );
}
