"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 stopProducts = CTX.state.stopProducts;
  const pager = CTX.state.pager;
  const productsLength = CTX.state.products?.length ?? 0;
  console.log("stopProducts-handleInfiniteNextFetchProducts", productsLength);
  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${
        params.id[0] != 0 ? `?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;
    console.log("runeed-handleInfiniteNextFetchProducts", nextPage);

    // Fetch products for the next page

    CTX.fetchProducts(
      nextPage,
      params.id[0] != 0 ? params.id[0] : "",
      selectedBrands,
      isChecked,
      rangePrice,
      rangePrice,
      sortBy != -1 ? sortBy : "",
      isRangePrice
    );

    // Update the pageGetProducts state for the next fetch
    CTX.setPageGetProducts(nextPage);
  };

  const [loading, setLoading] = useState(true);
  const getData = async () => {
    setLoading(true);
    await CTX.fetchProducts(0, params.id[0] != 0 ? params.id[0] : "");
    await fetchBarnds();
    setLoading(false);
  };
  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: "smooth", // Optional: smooth scrolling behavior
    });

    getData();
  }, []);

  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.replace(/-/g, " ")}</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 ">
                {loading && <>در حال بارگیری</>}
                {true ? (
                  <>
                    {!loading && (
                      <InfiniteScroll
                        dataLength={productsLength}
                        next={handleInfiniteNextFetchProducts}
                        hasMore={!stopProducts}
                      >
                        <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.replace(/-/g, " ")}
              </h1>
            </div>
            <div>
              {loading && <>در حال بارگیری</>}
              {true ? (
                <>
                  {!loading && (
                    <InfiniteScroll
                      dataLength={productsLength}
                      next={handleInfiniteNextFetchProducts}
                      hasMore={!stopProducts}
                      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 />
    </>
  );
}
