import { useState, useEffect, useRef } from 'react';
import { useAppDispatch, useAppSelector } from '@/app/hooks/useDispatch';
import { updateCampaignEventHubFormAlt } from '@/app/redux/features/main/campaigns/eventHubAction';

export const useCommuneSearch = () => {
  const dispatch = useAppDispatch();
  const { communeHubs } = useAppSelector((state) => state.eventhub);
  const [searchQuery, setSearchQuery] = useState('');
  const [showDropdown, setShowDropdown] = useState(false);
  const [filteredCommunes, setFilteredCommunes] = useState<any[]>([]);
  
  const dropdownRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (searchQuery.trim() === '') {
      setFilteredCommunes(communeHubs);
    } else {
      const filtered = communeHubs.filter(commune =>
        commune.commune_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        commune.postal_code.toString().includes(searchQuery) ||
        (commune.heading && commune.heading.toLowerCase().includes(searchQuery.toLowerCase()))
      );
      setFilteredCommunes(filtered);
    }
  }, [searchQuery, communeHubs]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowDropdown(false);
      }
    };

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

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchQuery(value);
    setShowDropdown(true);
  };

  const handleCommuneSelect = (commune: any) => {
    dispatch(updateCampaignEventHubFormAlt({ 
      key: "commune", 
      value: commune.commune_name 
    }));
      dispatch(updateCampaignEventHubFormAlt({ 
      key: "commune_id", 
      value: commune.commune_id 
    }));
      dispatch(updateCampaignEventHubFormAlt({ 
      key: "page_id", 
      value: commune.id 
    }));
    dispatch(updateCampaignEventHubFormAlt({ 
      key: "postcode", 
      value: commune.postal_code.toString() 
    }));
    dispatch(updateCampaignEventHubFormAlt({ 
      key: "title", 
      value: commune.heading || commune.commune_name 
    }));
    setSearchQuery(`${commune.commune_name}, ${commune.postal_code}`);
    setShowDropdown(false);
  };

  const handleInputFocus = () => {
    setShowDropdown(true);
  };
  const handleInputBlur = () => {
    setTimeout(() => setShowDropdown(false), 200);
  };

  // Clear search
  const clearSearch = () => {
    setSearchQuery('');
    setShowDropdown(false);
  };

  return {
    searchQuery,
    showDropdown,
    filteredCommunes,
    dropdownRef,
    handleSearchChange,
    handleCommuneSelect,
    handleInputFocus,
    handleInputBlur,
    clearSearch,
    setShowDropdown
  };
};