import { useState, useMemo } from "react";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { INITIAL_FILTERS } from "./constants";

export const useTradePanelFilters = () => {
  const [filters, setFilters] = useState(INITIAL_FILTERS);

  const updateFilter = (key, value) => {
    setFilters((prev) => ({ ...prev, [key]: value }));
  };

  const toggleArrayItem = (array, item) =>
    array.includes(item) ? array.filter((i) => i !== item) : [...array, item];

  const handleCityChange = (city) => {
    setFilters((prev) => ({
      ...prev,
      selectedCities: toggleArrayItem(prev.selectedCities, city),
    }));
  };

  const handleBreedChange = (breed) => {
    setFilters((prev) => ({
      ...prev,
      selectedBreeds: toggleArrayItem(prev.selectedBreeds, breed),
    }));
  };

  const handlePriceFilterSubmit = () => {
    setFilters((prev) => ({
      ...prev,
      minPrice: prev.tempMinPrice,
      maxPrice: prev.tempMaxPrice,
    }));
  };

  const handleAgeFilterSubmit = () => {
    setFilters((prev) => ({
      ...prev,
      minAge: prev.tempMinAge,
      maxAge: prev.tempMaxAge,
    }));
  };

  const {
    selectedCities,
    selectedBreeds,
    showRemaining,
    minPrice,
    maxPrice,
    minAge,
    maxAge,
  } = filters;

  const getExcelUrlParams = useMemo(() => {
    return (userKey, roleKey, textValue, page, perPage) => {
      const params = new URLSearchParams({
        key: userKey || "",
        breed: selectedBreeds?.join(",") || "",
        remain: showRemaining,
        min_age: minAge || "",
        max_age: maxAge || "",
        role: getRoleFromUrl() || "",
        search: "filter",
        value: textValue || "",
        page: page?.toString() || "1",
        page_size: perPage?.toString() || "20",
      });

      if (selectedCities?.length > 0) {
        params.append("city", selectedCities.join(","));
      }
      if (minPrice) params.append("min_amount", minPrice);
      if (maxPrice) params.append("max_amount", maxPrice);
      if (roleKey) params.append("role_key", roleKey);

      return params.toString();
    };
  }, [
    selectedBreeds,
    selectedCities,
    showRemaining,
    minPrice,
    maxPrice,
    minAge,
    maxAge,
  ]);

  return {
    filters,
    updateFilter,
    handleCityChange,
    handleBreedChange,
    handlePriceFilterSubmit,
    handleAgeFilterSubmit,
    selectedCities,
    selectedBreeds,
    showRemaining,
    minPrice,
    maxPrice,
    minAge,
    maxAge,
    getExcelUrlParams,
  };
};
