"use client";

import { useEffect, useState, useMemo, useRef } from "react";
import { useParams, useLocation, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Result, Button } from "antd";
import InfiniteScroll from "react-infinite-scroll-component";

import styles from "./CategoryPage.module.scss";
import ProductCard from "../../components/ProductCard/index";
import BrandSidebar from "../../components/BrandsSidebar/index";
import FilterSidebar from "../../components/FilterSideBar/index";
import Loader from "../../components/Loader/index";

import CategoryFilters from "./components/CategoryFilters";
import CategoryBreadcrumbs from "./components/CategoryBreadcrumbs";
import useCategoryData from "./hooks/useCategoryData";
import useCategoryProducts from "./hooks/useCategoryProducts";

const CategoryPage = () => {
  const { t } = useTranslation();
  const { categoryId, collectionId, brandId } = useParams();
  const location = useLocation();
  const navigate = useNavigate();

  const [pageState, setPageState] = useState({
    currentPage: 1,
    minPrice: "",
    maxPrice: "",
  });

  const [filterState, setFilterState] = useState({
    selectedFilterCategory: null,
    selectedFilterBrand: null,
    brandSearchQuery: "",
  });

  const routeKey = useMemo(
    () => `${categoryId || "x"}-${collectionId || "x"}-${brandId || "x"}`,
    [categoryId, collectionId, brandId]
  );

  const prevRouteRef = useRef(routeKey);
  const isInitialMount = useRef(true);

  const searchResults = location.state?.searchData?.data || [];
  const searchQuery = location.state?.searchQuery || null;

  const {
    categoriesData,
    selectedCategory,
    isSubCategory,
    filtersData,
    collectionData,
    isLoading: dataLoading,
    hasError: dataError,
    fetchFilters,
  } = useCategoryData({
    categoryId,
    collectionId,
    brandId,
    selectedFilterCategory: filterState.selectedFilterCategory,
    searchQuery,
  });

  const {
    products: allProducts,
    hasMore,
    isLoading: productsLoading,
    setProducts: setAllProducts,
    setHasMore,
  } = useCategoryProducts({
    categoryId,
    collectionId,
    brandId,
    selectedCategory,
    isSubCategory,
    currentPage: pageState.currentPage,
    selectedFilterCategory: filterState.selectedFilterCategory,
    selectedFilterBrand: filterState.selectedFilterBrand,
    minPrice: pageState.minPrice,
    maxPrice: pageState.maxPrice,
    searchQuery,
  });

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      prevRouteRef.current = routeKey;
      return;
    }

    if (prevRouteRef.current === routeKey) return;

    prevRouteRef.current = routeKey;

    setAllProducts([]);
    setHasMore(true);
    setPageState({ currentPage: 1, minPrice: "", maxPrice: "" });
    setFilterState({
      selectedFilterCategory: null,
      selectedFilterBrand: null,
      brandSearchQuery: "",
    });

    if (location.state?.clearFilters) {
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [
    routeKey,
    location.state?.clearFilters,
    navigate,
    setAllProducts,
    setHasMore,
  ]);

  const filteredProducts = useMemo(() => {
    let list = searchQuery ? searchResults : allProducts;

    if (pageState.minPrice || pageState.maxPrice) {
      const min = pageState.minPrice ? parseFloat(pageState.minPrice) : 0;
      const max = pageState.maxPrice
        ? parseFloat(pageState.maxPrice)
        : Infinity;
      list = list.filter((p) => {
        const price = p.price_amount || 0;
        return price >= min && price <= max;
      });
    }

    return list;
  }, [
    searchQuery,
    searchResults,
    allProducts,
    pageState.minPrice,
    pageState.maxPrice,
  ]);

  const totalItems = filteredProducts.length;

  const pageTitle = useMemo(() => {
    if (searchQuery) return `${t("search.resultsFor")}: "${searchQuery}"`;
    if (filterState.selectedFilterCategory) {
      const cat = findCategoryById(
        categoriesData?.data,
        filterState.selectedFilterCategory
      );
      return cat?.name || "Category";
    }
    if (brandId) return "Brand Products";
    if (selectedCategory) return selectedCategory.name;
    if (collectionData?.data?.name) return collectionData.data.name;
    return "Products";
  }, [
    searchQuery,
    filterState.selectedFilterCategory,
    brandId,
    selectedCategory,
    collectionData,
    categoriesData,
    t,
  ]);

  const handleFilterCategorySelect = (categoryId) => {
    setFilterState((prev) => ({
      ...prev,
      selectedFilterCategory: categoryId,
      selectedFilterBrand: null,
    }));

    setPageState({ currentPage: 1, minPrice: "", maxPrice: "" });
    setAllProducts([]);
    setHasMore(true);

    fetchFilters({ category_id: categoryId });
  };

  const handleFilterCategoryDeselect = () => {
    setFilterState((prev) => ({
      ...prev,
      selectedFilterCategory: null,
    }));

    setPageState({ currentPage: 1, minPrice: "", maxPrice: "" });
    setAllProducts([]);
    setHasMore(true);

    if (categoryId) fetchFilters({ category_id: categoryId });
  };

  const handleFilterBrandSelect = (brandId) => {
    setFilterState((prev) => ({
      ...prev,
      selectedFilterBrand: brandId,
    }));

    setPageState({ currentPage: 1, minPrice: "", maxPrice: "" });
    setAllProducts([]);
    setHasMore(true);
  };

  const handleFilterBrandDeselect = () => {
    setFilterState((prev) => ({
      ...prev,
      selectedFilterBrand: null,
    }));

    setPageState({ currentPage: 1, minPrice: "", maxPrice: "" });
    setAllProducts([]);
    setHasMore(true);
  };

  const handleCategoryClick = (targetId) => {
    setFilterState({
      selectedFilterCategory: null,
      selectedFilterBrand: null,
      brandSearchQuery: "",
    });
    setPageState({ currentPage: 1, minPrice: "", maxPrice: "" });
    setAllProducts([]);
    setHasMore(true);

    navigate(`/category/${targetId}`, {
      replace: false,
      state: { clearFilters: true, timestamp: Date.now() },
    });
  };

  const loadMoreData = () => {
    if (!hasMore || productsLoading) return;
    setPageState((prev) => ({ ...prev, currentPage: prev.currentPage + 1 }));
  };

  if (dataLoading) return <Loader />;
  if (dataError) {
    return (
      <Result
        status="500"
        title="500"
        subTitle="Näbelli ýalňyşlyk ýüze çykdy."
        extra={
          <Button type="primary" onClick={() => navigate("/")}>
            Baş sahypa gidiň
          </Button>
        }
      />
    );
  }

  const isInitialLoad =
    (productsLoading && allProducts.length === 0) ||
    (filterState.selectedFilterBrand &&
      allProducts.length === 0 &&
      productsLoading);

  return (
    <div className={styles.categoryPage}>
      {(categoryId || filterState.selectedFilterCategory) && (
        <CategoryBreadcrumbs
          categoriesData={categoriesData}
          categoryId={filterState.selectedFilterCategory || categoryId}
          onCategoryClick={handleCategoryClick}
        />
      )}

      <h2>{pageTitle}</h2>
      <p className={styles.sum}>
        {t("category.total")}: {totalItems} {t("category.items")}
      </p>

      <div className={styles.bars}>
        <button className={styles.sum}>
          <strong>{t("category.total")}:</strong> <br />
          {totalItems} {t("category.items")}
        </button>
        <BrandSidebar
          brands={filtersData?.brands || []}
          selectedBrand={filterState.selectedFilterBrand}
          onBrandSelect={handleFilterBrandSelect}
          onBrandDeselect={handleFilterBrandDeselect}
        />
        {/* <FilterSidebar onPriceSortChange={() => {}} currentPriceSort="none" /> */}
      </div>

      {selectedCategory?.children && !searchQuery && (
        <div className={styles.subCategories}>
          {selectedCategory.children.map((sub) => (
            <button key={sub.id} onClick={() => handleCategoryClick(sub.id)}>
              {sub.name}
            </button>
          ))}
        </div>
      )}

      <div className={styles.Container}>
        <CategoryFilters
          filtersData={filtersData}
          selectedFilterCategory={filterState.selectedFilterCategory}
          selectedFilterBrand={filterState.selectedFilterBrand}
          brandSearchQuery={filterState.brandSearchQuery}
          searchQuery={searchQuery}
          onCategorySelect={handleFilterCategorySelect}
          onCategoryDeselect={handleFilterCategoryDeselect}
          onBrandSelect={handleFilterBrandSelect}
          onBrandDeselect={handleFilterBrandDeselect}
          onBrandSearchChange={(query) =>
            setFilterState((prev) => ({ ...prev, brandSearchQuery: query }))
          }
        />

        <main className={styles.productsContainer}>
          {isInitialLoad ? (
            <div className={styles.loaderContainer}>
              <Loader />
            </div>
          ) : filteredProducts.length > 0 ? (
            <InfiniteScroll
              dataLength={filteredProducts.length}
              next={loadMoreData}
              hasMore={hasMore}
              scrollThreshold={0.8}
              loader={
                <div className={styles.loaderContainer}>
                  <Loader />
                </div>
              }
              className={styles.productGrid}
            >
              {filteredProducts.map((product) => (
                <ProductCard
                  key={product.id}
                  product={product}
                  showFavoriteButton
                  showAddToCart
                />
              ))}
            </InfiniteScroll>
          ) : (
            <div>{t("search.noResults")}</div>
          )}
        </main>
      </div>
    </div>
  );
};

function findCategoryById(categories, targetId) {
  if (!categories) return null;
  for (const cat of categories) {
    if (cat.id === targetId) return cat;
    if (cat.children) {
      const found = findCategoryById(cat.children, targetId);
      if (found) return found;
    }
  }
  return null;
}

export default CategoryPage;
