import React, { useState, useRef, useEffect } from 'react';
import clsx from 'clsx';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useGlobalSearch, SearchResult } from '@/api/hooks';
import { Search } from 'lucide-react';

export interface SearchDropdownProps {
  placeholder?: string;
}

function highlightMatch(text: string, query: string): React.ReactNode {
  if (!query.trim()) return text;
  const idx = text.toLowerCase().indexOf(query.toLowerCase());
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <mark className="bg-warning-200 text-secondary-900 rounded px-0.5">{text.slice(idx, idx + query.length)}</mark>
      {text.slice(idx + query.length)}
    </>
  );
}

export function SearchDropdown({ placeholder }: SearchDropdownProps) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [query, setQuery] = useState('');
  const [debouncedQuery, setDebouncedQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [activeIndex, setActiveIndex] = useState(-1);
  const containerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const { data: results, isLoading } = useGlobalSearch(debouncedQuery);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedQuery(query), 300);
    return () => clearTimeout(timer);
  }, [query]);

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

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!results || results.length === 0) return;
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setActiveIndex((prev) => Math.min(prev + 1, results.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActiveIndex((prev) => Math.max(prev - 1, 0));
    } else if (e.key === 'Enter' && activeIndex >= 0) {
      e.preventDefault();
      const result = results[activeIndex];
      navigate(result.url);
      setOpen(false);
      setQuery('');
    } else if (e.key === 'Escape') {
      setOpen(false);
      inputRef.current?.blur();
    }
  };

  const handleResultClick = (result: SearchResult) => {
    navigate(result.url);
    setOpen(false);
    setQuery('');
  };

  const handleSeeAll = () => {
    navigate(`/search?q=${encodeURIComponent(query)}`);
    setOpen(false);
  };

  return (
    <div ref={containerRef} className="relative w-full" data-testid="search-dropdown">
      <input
        ref={inputRef}
        type="search"
        value={query}
        onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }}
        onFocus={() => query && setOpen(true)}
        onKeyDown={handleKeyDown}
        placeholder={placeholder || t('topbar.search')}
        className="w-64 pl-10 pr-3 py-1 text-sm rounded-md border border-secondary-300 focus:outline-none focus:ring-2 focus:ring-primary-500"
        aria-label={t('topbar.search')}
        role="combobox"
        aria-expanded={open}
        aria-controls="search-results-list"
        aria-autocomplete="list"
      />
      <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-secondary-400" aria-hidden="true" strokeWidth={2} />
      {open && query.trim() && (
        <div
          className="absolute top-full left-0 mt-1 w-96 bg-white rounded-md shadow-lg border border-secondary-200 z-50 max-h-96 overflow-y-auto"
          role="listbox"
          id="search-results-list"
          data-testid="search-results"
        >
          {isLoading ? (
            <div className="px-4 py-3 text-sm text-secondary-500">{t('common.loading')}</div>
          ) : results && results.length > 0 ? (
            <>
              <ul className="py-1">
                {results.map((result, idx) => (
                  <li key={`${result.type}-${result.id}`}>
                    <button
                      onClick={() => handleResultClick(result)}
                      onMouseEnter={() => setActiveIndex(idx)}
                      className={clsx(
                        'w-full text-left px-4 py-2 text-sm hover:bg-secondary-50 min-h-touch flex items-center gap-3',
                        activeIndex === idx && 'bg-primary-50'
                      )}
                      role="option"
                      aria-selected={activeIndex === idx}
                    >
                      <span className={clsx(
                        'inline-flex items-center justify-center w-8 h-8 rounded-full text-xs font-semibold flex-shrink-0',
                        result.type === 'company' ? 'bg-primary-100 text-primary-700' : 'bg-accent-100 text-accent-700'
                      )} aria-hidden="true">
                        {result.type === 'company' ? 'F' : 'K'}
                      </span>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-secondary-900 truncate">{highlightMatch(result.name, query)}</p>
                        {result.description && (
                          <p className="text-xs text-secondary-500 truncate">{highlightMatch(result.description, query)}</p>
                        )}
                      </div>
                    </button>
                  </li>
                ))}
              </ul>
              <div className="border-t border-secondary-200 px-4 py-2">
                <button
                  onClick={handleSeeAll}
                  className="text-sm text-primary-600 hover:text-primary-700 font-medium min-h-touch"
                >
                  Alle Ergebnisse anzeigen →
                </button>
              </div>
            </>
          ) : (
            <div className="px-4 py-3 text-sm text-secondary-500">{t('common.noResults')}</div>
          )}
        </div>
      )}
    </div>
  );
}
