import { useState, useCallback, useEffect } from "react";
import { useGetBrandProducts } from "./useBrandData";
import { CategoryVariant } from "../types/Types";

interface UseBrandFiltersDataProps {
  brandId: string;
}

export const useBrandFiltersData = ({ brandId }: UseBrandFiltersDataProps) => {
  const [filterState, setFilterState] = useState<{
    categories: string[];
    priceRange: [number, number];
  }>({
    categories: [],
    priceRange: [0, 8000000],
  });

  const { data, isLoading } = useGetBrandProducts({
    brandId,
    page: 1,
    limit: 20,
    category:
      filterState.categories.length > 0
        ? filterState.categories.join(",")
        : undefined,
    priceMin:
      filterState.priceRange[0] > 0 ? filterState.priceRange[0] : undefined,
    priceMax:
      filterState.priceRange[1] < 8000000
        ? filterState.priceRange[1]
        : undefined,
    sort: 3,
  });

  // بروزرسانی محدوده قیمت از API
  useEffect(() => {
    if (data?.results?.filters?.priceRange) {
      const { minPrice, maxPrice } = data.results.filters.priceRange;
      setFilterState((prev) => ({
        ...prev,
        priceRange: [minPrice, maxPrice],
      }));
    }
  }, [data?.results?.filters?.priceRange]);

  // نمایش دسته اصلی برند برای ساختار درختی
  const categories: CategoryVariant[] = data?.results?.category
    ? [data.results.category as CategoryVariant]
    : [];

  const priceMinMaxRange = data?.results?.filters?.priceRange || {
    minPrice: 0,
    maxPrice: 8000000,
  };

  const applyCategoryFilter = useCallback((categoryId: string) => {
    setFilterState((prev) => ({
      ...prev,
      categories: prev.categories.includes(categoryId)
        ? prev.categories.filter((id) => id !== categoryId)
        : [...prev.categories, categoryId],
    }));
  }, []);

  const updatePriceRange = useCallback((range: [number, number]) => {
    setFilterState((prev) => ({
      ...prev,
      priceRange: range,
    }));
  }, []);

  const clearAllFilters = useCallback(() => {
    const defaultPriceRange = data?.results?.filters?.priceRange
      ? [
          data.results.filters.priceRange.minPrice,
          data.results.filters.priceRange.maxPrice,
        ]
      : [0, 8000000];
    setFilterState({
      categories: [],
      priceRange: defaultPriceRange as [number, number],
    });
  }, [data?.results?.filters?.priceRange]);

  return {
    filterState,
    categories,
    isLoading,
    priceMinMaxRange,
    applyCategoryFilter,
    updatePriceRange,
    clearAllFilters,
  };
};
