import { useState, useEffect } from 'react';
import { searchGuests } from '../services/guestService';
import type { Guest } from '../types/guest';

type Filter = 'all' | 'checked' | 'pending';

const DEBOUNCE_MS = 150;

export function useSearch(filter: Filter = 'all') {
  const [query, setQuery]       = useState('');
  const [results, setResults]   = useState<Guest[]>([]);
  const [isSearching, setIsSearching] = useState(false);

  useEffect(() => {
    const q = query.trim();
    if (!q) {
      setResults([]);
      setIsSearching(false);
      return;
    }

    setIsSearching(true);

    const timer = setTimeout(() => {
      try {
        let found = searchGuests(q);
        
        // Apply filter
        if (filter === 'checked') {
          found = found.filter(g => g.checked_in_count > 0);
        } else if (filter === 'pending') {
          found = found.filter(g => g.checked_in_count < g.total_attendees);
        }
        
        setResults(found);
      } catch {
        setResults([]);
      } finally {
        setIsSearching(false);
      }
    }, DEBOUNCE_MS);

    return () => clearTimeout(timer);
  }, [query, filter]);

  const clear = () => {
    setQuery('');
    setResults([]);
  };

  return { query, setQuery, results, setResults, isSearching, clear };
}
