// hooks/useCitySearch.ts
import { useState, useEffect, useRef, useCallback } from 'react';
import { useAppDispatch } from '@/app/hooks/useDispatch';
import { updateCampaignCategoryFormAlt } from '@/app/redux/features/main/campaigns/categoryAction';

interface City {
  state_id: string;
  state_name: string;
  country_name: string;
  city_name: string;
  city_id: string;
  country_id: string;
  postal_code: string;
  lat: string;
  lng: string;
}

export const useCitySearch = () => {
  const [citySearchQuery, setCitySearchQuery] = useState('');
  const [filteredCities, setFilteredCities] = useState<City[]>([]);
  const [showCityDropdown, setShowCityDropdown] = useState(false);
  const [isCityLoading, setIsCityLoading] = useState(false);
  const cityDropdownRef = useRef<HTMLDivElement>(null);
  const dispatch = useAppDispatch();

  // Debounce function
  const debounce = (func: Function, delay: number) => {
    let timeoutId: NodeJS.Timeout;
    return (...args: any[]) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func.apply(null, args), delay);
    };
  };

  // Fetch cities from API
  const fetchCities = async (query: string) => {
    if (!query || query.length < 2) {
      setFilteredCities([]);
      setShowCityDropdown(false);
      return;
    }

    setIsCityLoading(true);
    try {
      const response = await fetch(
        `https://admin.eventx.fr/api/get-state-with-country?search_keyword=${encodeURIComponent(query)}`
      );
      
      if (!response.ok) {
        throw new Error('Failed to fetch cities');
      }

      const data = await response.json();
      
      if (data.status === 200 && data.getResult) {
        setFilteredCities(data.getResult);
        setShowCityDropdown(data.getResult.length > 0);
      } else {
        setFilteredCities([]);
        setShowCityDropdown(false);
      }
    } catch (error) {
      console.error('Error fetching cities:', error);
      setFilteredCities([]);
      setShowCityDropdown(false);
    } finally {
      setIsCityLoading(false);
    }
  };

  // Debounced search function
  const debouncedSearch = useCallback(
    debounce((query: string) => {
      fetchCities(query);
    }, 300), // 300ms debounce delay
    []
  );

  // Handle search input change
  const handleCitySearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setCitySearchQuery(value);
    debouncedSearch(value);
  };

  // Handle city selection
  const handleCitySelect = (city: City) => {
    setCitySearchQuery(city.city_name);
    setShowCityDropdown(false);
    
    // Update the form with the selected city
    dispatch(
      updateCampaignCategoryFormAlt({ 
        key: "activity_commune", 
        value: city.city_name 
      })
    );
  };

  // Handle input focus
  const handleCityInputFocus = () => {
    if (citySearchQuery.length >= 2 && filteredCities.length > 0) {
      setShowCityDropdown(true);
    }
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (cityDropdownRef.current && !cityDropdownRef.current.contains(event.target as Node)) {
        setShowCityDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return {
    citySearchQuery,
    filteredCities,
    showCityDropdown,
    isCityLoading,
    cityDropdownRef,
    handleCitySearchChange,
    handleCitySelect,
    handleCityInputFocus,
    setShowCityDropdown,
  };
};