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

export const useCommuneSearch = () => {
  const dispatch = useAppDispatch();
  const { communeHubs } = useAppSelector((state) => state.category);

  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(
        (category) =>
          category.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          (category.description &&
            category.description
              .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 = (category: any) => {
    dispatch(
      updateCampaignCategoryFormAlt({
        key: "category",
        value: category.name,
      })
    );
    dispatch(
      updateCampaignCategoryFormAlt({
        key: "category_id",
        value: category.id.toString(),
      })
    );
    // dispatch(updateCampaignCategoryFormAlt({
    //   key: "title",
    //   value: category.name
    // }));
    setSearchQuery(category.name);
    setShowDropdown(false);
  };

  const handleInputFocus = () => {
    setShowDropdown(true);
  };

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

  const clearSearch = () => {
    setSearchQuery("");
    setShowDropdown(false);
  };

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