import { useState, useEffect, useMemo } from "react";
import { useGetCategoriesQuery } from "../../../app/api/categories";
import { useGetCollectionByIdQuery } from "../../../app/api/collectionsApi";
import {
  useGetFiltersQuery,
  useLazyGetFiltersQuery,
} from "../../../app/api/filtersApi";

const useCategoryData = ({
  categoryId,
  collectionId,
  brandId,
  selectedFilterCategory,
  searchQuery,
}) => {
  const [selectedCategory, setSelectedCategory] = useState(null);

  const { data: categoriesData } = useGetCategoriesQuery("tree");

  const filterParams = useMemo(() => {
    if (searchQuery) return null;
    if (selectedFilterCategory) return { category_id: selectedFilterCategory };
    if (categoryId) return { category_id: categoryId };
    if (collectionId) return { collection_id: collectionId };
    if (brandId) return { brand_id: brandId };
    return null;
  }, [categoryId, collectionId, brandId, selectedFilterCategory, searchQuery]);

  const {
    data: filtersData,
    isLoading: filtersLoading,
    error: filtersError,
  } = useGetFiltersQuery(filterParams, {
    skip: !filterParams,
  });

  const [fetchFilters, { data: lazyFiltersData }] = useLazyGetFiltersQuery();

  const {
    data: collectionData,
    isLoading: collectionLoading,
    error: collectionError,
  } = useGetCollectionByIdQuery(collectionId, {
    skip: !collectionId,
  });

  const isSubCategory = useMemo(() => {
    if (!categoriesData?.data || !categoryId) return false;

    const checkIsSubCategory = (categories, targetId) => {
      for (const category of categories) {
        if (category.children) {
          for (const subCategory of category.children) {
            if (subCategory.id === parseInt(targetId)) return true;
            if (subCategory.children) {
              const found = checkIsSubCategory([subCategory], targetId);
              if (found) return true;
            }
          }
        }
      }
      return false;
    };

    return checkIsSubCategory(categoriesData.data, parseInt(categoryId));
  }, [categoriesData, categoryId]);

  const activeFilters = useMemo(() => {
    return selectedFilterCategory && lazyFiltersData
      ? lazyFiltersData
      : filtersData;
  }, [selectedFilterCategory, lazyFiltersData, filtersData]);

  useEffect(() => {
    if (!categoryId || !categoriesData?.data) {
      setSelectedCategory(null);
      return;
    }

    const findCategory = (categories, targetId) => {
      for (const cat of categories) {
        if (cat.id === parseInt(targetId)) return cat;
        if (cat.children) {
          const found = findCategory(cat.children, targetId);
          if (found) return found;
        }
      }
      return null;
    };

    const category = findCategory(categoriesData.data, parseInt(categoryId));
    setSelectedCategory(category);
  }, [categoryId, categoriesData]);

  const isLoading = filtersLoading || collectionLoading;
  const hasError = filtersError || collectionError;

  return {
    categoriesData,
    selectedCategory,
    isSubCategory,
    filtersData: activeFilters,
    collectionData,
    isLoading,
    hasError,
    fetchFilters,
  };
};

export default useCategoryData;
