import { useState, useRef, useEffect } from 'react';

interface SearchResult {
  id: string;
  slug: string;
  name: string;
  brand: string;
  colorway: string;
  image: string;
  lowestPrice: number;
  shopCount: number;
}

interface Suggestion {
  brands: Array<{ name: string; slug: string; count: number }>;
  models: Array<{ name: string; brand: string; brand_slug: string; slug: string; count: number }>;
  products: Array<{ id: string; slug: string; name: string; brand: string; price: number; shops: number }>;
}

export default function SearchBar({ large = false }: { large?: boolean }) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [suggestions, setSuggestions] = useState<Suggestion | null>(null);
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  useEffect(() => {
    if (query.length < 2) { setResults([]); setSuggestions(null); return; }
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      try {
        // Fetch both search results and suggestions in parallel
        const [searchRes, suggestRes] = await Promise.all([
          fetch(`/api/search?q=${encodeURIComponent(query)}`),
          fetch(`/api/search/suggest?q=${encodeURIComponent(query)}`),
        ]);
        if (searchRes.ok) setResults(await searchRes.json());
        if (suggestRes.ok) setSuggestions(await suggestRes.json());
      } catch {}
    }, 200);
    return () => clearTimeout(debounceRef.current);
  }, [query]);

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

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && query.trim().length >= 2) {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: 'search', search_term: query.trim() });
      setOpen(false);
      window.location.href = `/zoeken?q=${encodeURIComponent(query.trim())}`;
    }
  };

  const searchUrl = `/zoeken?q=${encodeURIComponent(query.trim())}`;
  const hasSuggestions = suggestions && (suggestions.brands.length > 0 || suggestions.models.length > 0);
  const hasResults = results.length > 0;
  const showDropdown = open && (hasSuggestions || hasResults);

  return (
    <div ref={ref} className="relative z-[60] w-full">
      <div className={`relative flex items-center rounded-2xl border border-[var(--border)]/50 bg-[var(--bg-card)] transition-all focus-within:border-[var(--accent)]/50 focus-within:shadow-lg focus-within:shadow-[var(--accent)]/5 ${large ? 'px-5 py-4' : 'px-4 py-2.5'}`}>
        <svg className="mr-3 h-5 w-5 shrink-0 text-[var(--text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        <input
          type="search"
          value={query}
          onChange={e => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          onKeyDown={handleKeyDown}
          placeholder="Zoek sneakers, merken of modellen..."
          className={`w-full bg-transparent text-[var(--text)] placeholder-[var(--text-muted)] outline-none ${large ? 'text-lg' : 'text-sm'}`}
          aria-label="Zoek sneakers"
        />
        {query && (
          <button onClick={() => { setQuery(''); setOpen(false); }} className="ml-2 text-[var(--text-muted)] hover:text-[var(--text)]" aria-label="Zoekopdracht wissen">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        )}
      </div>

      {showDropdown && (
        <div className="absolute left-0 right-0 top-full z-[100] mt-2 overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--bg-card)] shadow-2xl max-h-[70vh] overflow-y-auto">
          {/* Brand suggestions */}
          {suggestions && suggestions.brands.length > 0 && (
            <div className="px-4 pt-3 pb-1">
              <p className="text-[10px] font-bold uppercase tracking-widest text-[var(--text-muted)] mb-2">Merken</p>
              <div className="flex flex-wrap gap-1.5 pb-2">
                {suggestions.brands.map(b => (
                  <a
                    key={b.slug}
                    href={`/merken/${b.slug}`}
                    className="inline-flex items-center gap-1.5 rounded-full border border-[var(--border)]/50 bg-[var(--bg-elevated)] px-3 py-1 text-xs font-semibold text-[var(--text-secondary)] hover:border-[var(--accent)]/40 hover:text-[var(--accent)] transition-all"
                  >
                    {b.name}
                    <span className="text-[var(--text-muted)]">{b.count}</span>
                  </a>
                ))}
              </div>
            </div>
          )}

          {/* Model suggestions */}
          {suggestions && suggestions.models.length > 0 && (
            <div className="px-4 pt-2 pb-1 border-t border-[var(--border)]">
              <p className="text-[10px] font-bold uppercase tracking-widest text-[var(--text-muted)] mb-2">Modellen</p>
              {suggestions.models.map(m => (
                <a
                  key={`${m.brand_slug}-${m.slug}`}
                  href={`/merken/${m.brand_slug}/${m.slug}`}
                  className="flex items-center justify-between px-1 py-1.5 text-sm hover:text-[var(--accent)] transition-colors"
                >
                  <span>
                    <span className="text-[var(--text-muted)] text-xs mr-1">{m.brand}</span>
                    <span className="font-semibold text-[var(--text)]">{m.name}</span>
                  </span>
                  <span className="text-xs text-[var(--text-muted)]">{m.count} varianten</span>
                </a>
              ))}
            </div>
          )}

          {/* Product results */}
          {hasResults && (
            <div className={hasSuggestions ? 'border-t border-[var(--border)]' : ''}>
              {hasSuggestions && (
                <p className="px-4 pt-3 pb-1 text-[10px] font-bold uppercase tracking-widest text-[var(--text-muted)]">Producten</p>
              )}
              {results.slice(0, 6).map(s => (
                <a
                  key={s.id}
                  href={`/sneakers/${s.slug}`}
                  className="flex items-center gap-4 px-4 py-3 transition-colors hover:bg-[var(--bg-hover)]"
                  onClick={() => {
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push({ ecommerce: null });
                    window.dataLayer.push({
                      event: 'select_item',
                      ecommerce: { items: [{ item_id: s.id, item_name: `${s.brand} ${s.name}`, item_brand: s.brand, price: s.lowestPrice }] }
                    });
                  }}
                >
                  <img src={s.image} alt="" width={48} height={48} className="h-12 w-12 rounded-lg bg-[var(--bg-elevated)] object-contain" loading="lazy" decoding="async" />
                  <div className="min-w-0 flex-1">
                    <div className="truncate text-sm font-semibold text-[var(--text)]">{s.brand} {s.name}</div>
                    <div className="text-xs text-[var(--text-muted)]">{s.colorway}{s.shopCount > 0 && ` · ${s.shopCount} shops`}</div>
                  </div>
                  <div className="text-sm font-bold text-[var(--accent)]">€{s.lowestPrice.toFixed(2).replace('.', ',')}</div>
                </a>
              ))}
            </div>
          )}

          <a
            href={searchUrl}
            onClick={() => { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'search', search_term: query.trim() }); }}
            className="flex items-center justify-center gap-2 border-t border-[var(--border)] px-4 py-3 text-sm font-semibold text-[var(--accent)] transition-colors hover:bg-[var(--bg-hover)]"
          >
            Bekijk alle resultaten
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
            </svg>
          </a>
        </div>
      )}
    </div>
  );
}
