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

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

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

  useEffect(() => {
    if (query.length < 2) { setResults([]); return; }
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
        if (res.ok) setResults(await res.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) {
      // Push search event to dataLayer
      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 handleViewAll = () => {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event: 'search', search_term: query.trim() });
  };

  return (
    <div ref={ref} className="relative z-[60] w-full">
      <div className={`relative flex items-center rounded-2xl border border-border/50 bg-bg-card transition-all focus-within:border-accent/50 focus-within:shadow-lg focus-within:shadow-accent/5 ${large ? 'px-5 py-4' : 'px-4 py-2.5'}`}>
        <svg className="mr-3 h-5 w-5 shrink-0 text-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="text"
          value={query}
          onChange={e => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          onKeyDown={handleKeyDown}
          placeholder="Zoek sneakers..."
          className={`w-full bg-transparent text-text placeholder-text-muted outline-none ${large ? 'text-lg' : 'text-sm'}`}
          aria-label="Zoek sneakers"
        />
        {query && (
          <button onClick={() => { setQuery(''); setOpen(false); }} className="ml-2 text-text-muted hover:text-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>

      {open && results.length > 0 && (
        <div className="absolute left-0 right-0 top-full z-[100] mt-2 overflow-hidden rounded-2xl border border-border/50 bg-bg-card shadow-2xl">
          {results.map(s => (
            <a
              key={s.id}
              href={`/sneakers/${s.slug}`}
              className="flex items-center gap-4 px-4 py-3 transition-colors hover:bg-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="" className="h-12 w-12 rounded-lg bg-bg-elevated object-contain" />
              <div className="min-w-0 flex-1">
                <div className="truncate text-sm font-semibold text-text">{s.brand} {s.name}</div>
                <div className="text-xs text-text-muted">{s.colorway}{s.shopCount > 0 && ` · ${s.shopCount} ${s.shopCount === 1 ? 'winkel' : 'winkels'}`}</div>
              </div>
              <div className="text-sm font-bold text-accent">€{s.lowestPrice.toFixed(2).replace('.', ',')}</div>
            </a>
          ))}
          <a
            href={searchUrl}
            onClick={handleViewAll}
            className="flex items-center justify-center gap-2 border-t border-border/30 px-4 py-3 text-sm font-semibold text-accent transition-colors hover:bg-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>
  );
}
