import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { EmailSuggestionsService } from "@/services/EmailSuggestionsService";

export const useEmailSuggestions = () => {
  const [debouncedQuery, setDebouncedQuery] = useState("");

  const { data: suggestionsData, isLoading, error } = useQuery({
    queryKey: ["emailSuggestions", debouncedQuery],
    queryFn: () =>
      EmailSuggestionsService.getSuggestions({
        query: debouncedQuery,
        limit: 5,
      }),
    enabled: debouncedQuery.length >= 2,
    staleTime: 1000 * 60 * 5, // 5 minutes
  });

  if (error) {
    console.error("🔥 Query error:", error);
  }

  const searchSuggestions = (query: string) => {
    // Debounce the actual search
    const timeoutId = setTimeout(() => {
      setDebouncedQuery(query);
    }, 300);

    return () => clearTimeout(timeoutId);
  };

  const suggestions = suggestionsData?.suggestions || [];

  return {
    suggestions,
    searchSuggestions,
    isLoading,
    hasResults: suggestions.length > 0,
  };
};
