import { useState, useCallback } from 'react';
import { adminApi } from '@/services/adminApi';
import { useToast } from '@/hooks/use-toast';

interface SearchFilters {
  category?: string;
  type?: string;
  minRating?: number;
  verified?: boolean;
}

export const useSearch = () => {
  const [searching, setSearching] = useState(false);
  const [results, setResults] = useState<any[]>([]);
  const { toast } = useToast();

  const searchPlaces = useCallback(async (query: string, filters?: SearchFilters) => {
    if (!query.trim()) {
      setResults([]);
      return;
    }

    setSearching(true);
    try {
      const response = await adminApi.searchPlaces(query, {
        category: filters?.category,
        minRating: filters?.minRating,
      });
      setResults(response as any);
    } catch (error) {
      console.error('Error searching places:', error);
      toast({
        title: 'Error de búsqueda',
        description: error instanceof Error ? error.message : 'No se pudo realizar la búsqueda',
        variant: 'destructive',
      });
      setResults([]);
    } finally {
      setSearching(false);
    }
  }, [toast]);

  const searchEstablishments = useCallback(async (query: string, filters?: SearchFilters) => {
    if (!query.trim()) {
      setResults([]);
      return;
    }

    setSearching(true);
    try {
      const response = await adminApi.searchEstablishments(query, {
        type: filters?.type,
        minRating: filters?.minRating,
        verified: filters?.verified,
      });
      setResults(response as any);
    } catch (error) {
      console.error('Error searching establishments:', error);
      toast({
        title: 'Error de búsqueda',
        description: error instanceof Error ? error.message : 'No se pudo realizar la búsqueda',
        variant: 'destructive',
      });
      setResults([]);
    } finally {
      setSearching(false);
    }
  }, [toast]);

  const clearResults = useCallback(() => {
    setResults([]);
  }, []);

  return {
    searching,
    results,
    searchPlaces,
    searchEstablishments,
    clearResults,
  };
};
