"use client";

import FilterCategory from "@comp/Category/FilterCategory/page";
import ListProdocts from "@comp/Category/ListProdocts/page";
import FilterCategoryMobile from "@comp/Category/Mobile/FilterCategoryMobile/page";
import ListProductsMobile from "@comp/Category/Mobile/ListProductsMobile/page";
import PaginationCategoory from "@comp/Category/PaginationCategoory/page";
import Footer from "@comp/Footer/page";
import Navbar from "@comp/Navbar/page";
import AppContext from "@ctx/AppContext";
import { useContext, useEffect, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";

export default function CategoriesData({ params }) {
  console.log("params", params.id[0]);

  const CTX = useContext(AppContext);
  const pageGetProducts = CTX.state.pageGetProducts;
  const stopGetTasks = CTX.state.stopGetTasks;
  const pager = CTX.state.pager;
  const filter = CTX.state.filter;

  const isChecked = CTX.state.isChecked;
  const selectedBrands = CTX.state.selectedBrands;
  const rangePrice = CTX.state.rangePrice;
  const isRangePrice = CTX.state.isRangePrice;
  const sortBy = CTX.state.sortBy;

  const fetchBarnds = async () => {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/brand?categoryId=${params.id[0]}`
    );
    const brands = await res.json();
    CTX.setBrands(brands);
  };

  const decodedName = decodeURIComponent(params.id[1]);

  const handleInfiniteNextFetchProducts = () => {
    // Increment the page number
    const nextPage = pageGetProducts + 1;

    // Fetch products for the next page
    CTX.fetchProducts(
      nextPage,
      params.id[0],
      selectedBrands,
      isChecked,
      rangePrice,
      rangePrice,
      sortBy,
      isRangePrice
    );

    // Update the pageGetProducts state for the next fetch
    CTX.setPageGetProducts(nextPage);
  };
  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: "smooth", // Optional: smooth scrolling behavior
    });
    CTX.fetchProducts(0, params.id[0]);
    fetchBarnds();
  }, []);

  console.log(pager?.totalPage > 1, pager?.totalPage);

  return (
    <>
      <div className=" pb-20">
        <Navbar theme={1} />
        {!CTX.state.isMobile && (
          <div className="xs:hidden lg:block">
            <div className="text-right px-8 py-5">
              <h1 className="font-medium ">{decodedName}</h1>
            </div>
            <div className="pl-20 pr-10 grid lg:grid-cols-8 xl:grid-cols-5 rtl mt-10  ">
              <FilterCategory
                id={params.id}
                isChecked={isChecked}
                selectedBrands={selectedBrands}
                rangePrice={rangePrice}
                sortBy={sortBy}
                isRangePrice={isRangePrice}
                filter={filter}
              />

              <div className="lg:col-span-6 xl:col-span-4 ">
                {true ? (
                  <InfiniteScroll
                    dataLength={20}
                    next={handleInfiniteNextFetchProducts}
                    hasMore={!stopGetTasks}
                  >
                    <ListProdocts
                      id={params.id}
                      isChecked={isChecked}
                      selectedBrands={selectedBrands}
                      rangePrice={rangePrice}
                      sortBy={sortBy}
                      isRangePrice={isRangePrice}
                    />
                  </InfiniteScroll>
                ) : (
                  <div className="flex justify-center py-5">
                    <div className="bg-white shadow  mt-5 w-fit rounded-full text-sm   p-4">
                      چیزی یافت نشد
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}

        {CTX.state.isMobile && (
          <div className="xs:block lg:hidden ">
            <FilterCategoryMobile
              id={params.id}
              isChecked={isChecked}
              selectedBrands={selectedBrands}
              rangePrice={rangePrice}
              sortBy={sortBy}
              isRangePrice={isRangePrice}
            />
            <div className="text-right px-8 py-5">
              <h1 className="font-medium text-sm ">{decodedName}</h1>
            </div>
            <div>
              {true ? (
                <InfiniteScroll
                  dataLength={20}
                  next={handleInfiniteNextFetchProducts}
                  hasMore={!stopGetTasks}
                  scrollThreshold={0.5}
                >
                  <ListProductsMobile
                    id={params.id}
                    isChecked={isChecked}
                    selectedBrands={selectedBrands}
                    rangePrice={rangePrice}
                    sortBy={sortBy}
                    isRangePrice={isRangePrice}
                  />
                </InfiniteScroll>
              ) : (
                <div className="flex justify-center py-5">
                  <div className="bg-white shadow  mt-5 w-fit rounded-full text-sm   p-4">
                    چیزی یافت نشد
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
      {pager?.totalPage > 1 && (
        <PaginationCategoory
          id={params.id}
          isChecked={isChecked}
          selectedBrands={selectedBrands}
          rangePrice={rangePrice}
          sortBy={sortBy}
          isRangePrice={isRangePrice}
        />
      )}

      <Footer />
    </>
  );
}
