"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, Drawer } from "antd";
import InfiniteScroll from "react-infinite-scroll-component";
import { LuFilter } from "react-icons/lu";

import styles from "./CategoryPage.module.scss";
import ProductCard from "../../components/ProductCard/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";

import MobilePhoneCard from "./components/Mobilephonecard";

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 [isFilterDrawerOpen, setIsFilterDrawerOpen] = useState(false);
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWindowWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

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

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

  const searchResults = useMemo(
    () => location.state?.searchData?.data || [],
    [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,
  });
  const isMobilePhoneView =
    (Number(categoryId) === 531 ||
      Number(filterState.selectedFilterCategory) === 531) &&
    windowWidth >= 768;
  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.filterButton}
          onClick={() => setIsFilterDrawerOpen(true)}
        >
          {t("category.filter")} <LuFilter />
        </button>
      </div>

      <Drawer
        title={t("category.filter")}
        placement="right"
        onClose={() => setIsFilterDrawerOpen(false)}
        open={isFilterDrawerOpen}
        width="80%"
      >
        <CategoryFilters
          filtersData={filtersData}
          selectedFilterCategory={filterState.selectedFilterCategory}
          selectedFilterBrand={filterState.selectedFilterBrand}
          brandSearchQuery={filterState.brandSearchQuery}
          searchQuery={searchQuery}
          minPrice={pageState.minPrice}
          maxPrice={pageState.maxPrice}
          onMinPriceChange={(value) => {
            setPageState((prev) => ({
              ...prev,
              minPrice: value,
              currentPage: 1,
            }));
            setAllProducts([]);
            setHasMore(true);
          }}
          onMaxPriceChange={(value) => {
            setPageState((prev) => ({
              ...prev,
              maxPrice: value,
              currentPage: 1,
            }));
            setAllProducts([]);
            setHasMore(true);
          }}
          onCategorySelect={handleFilterCategorySelect}
          onCategoryDeselect={handleFilterCategoryDeselect}
          onBrandSelect={handleFilterBrandSelect}
          onBrandDeselect={handleFilterBrandDeselect}
          onBrandSearchChange={(query) =>
            setFilterState((prev) => ({ ...prev, brandSearchQuery: query }))
          }
        />
      </Drawer>

      <div className={styles.Container}>
        <CategoryFilters
          className={styles.sidebar}
          filtersData={filtersData}
          selectedFilterCategory={filterState.selectedFilterCategory}
          selectedFilterBrand={filterState.selectedFilterBrand}
          brandSearchQuery={filterState.brandSearchQuery}
          searchQuery={searchQuery}
          minPrice={pageState.minPrice}
          maxPrice={pageState.maxPrice}
          onMinPriceChange={(value) => {
            setPageState((prev) => ({
              ...prev,
              minPrice: value,
              currentPage: 1,
            }));
            setAllProducts([]);
            setHasMore(true);
          }}
          onMaxPriceChange={(value) => {
            setPageState((prev) => ({
              ...prev,
              maxPrice: value,
              currentPage: 1,
            }));
            setAllProducts([]);
            setHasMore(true);
          }}
          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} ${
                isMobilePhoneView ? styles.mobilePhoneGrid : ""
              }`}
            >
              {filteredProducts.map((product) =>
                isMobilePhoneView ? (
                  <MobilePhoneCard
                    key={product.id}
                    product={product}
                    showFavoriteButton
                    showAddToCart
                  />
                ) : (
                  <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;
