"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 { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useContext, useEffect, useMemo, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";

export default function CategoriesData({ params, products }) {
  const CTX = useContext(AppContext);
  const searchParams = useSearchParams();

  useEffect(() => {
    if (
      Number(searchParams.get("page")) === 0 ||
      !Number(searchParams.get("page")) ||
      CTX.state.stopProducts
    ) {
      CTX.setProducts(products.products);
    } else {
      CTX.setProducts([...CTX.state.products, ...products.products]);
    }
    CTX.setStopProducts(
      CTX.state.stopProducts || products?.products?.length < 20
    );
    CTX.setPager(products.pager);
    CTX.setFilter(products.filters);
  }, [products]);

  const pageGetProducts = useMemo(
    () => (searchParams.get("page") ? Number(searchParams.get("page")) : 0),
    [searchParams]
  );
  const stopProducts = CTX.state.stopProducts;
  const pager = products.pager;
  const productsLength = CTX.state.products.length;
  const filter = CTX.state.filter;

  const isChecked = useMemo(
    () => Boolean(Number(searchParams.get("isActive"))),
    [searchParams]
  );
  const selectedBrands = useMemo(
    () =>
      searchParams.get("brandIds")
        ? searchParams.get("brandIds").split(",")
        : [],
    [searchParams]
  );
  const rangePrice = useMemo(
    () => [
      searchParams.get("maxPrice")
        ? Number(searchParams.get("maxPrice"))
        : filter?.price?.maximumValue,
      searchParams.get("minPrice")
        ? Number(searchParams.get("minPrice"))
        : filter?.price?.minimumValue,
    ],
    [searchParams]
  );
  const isRangePrice = CTX.state.isRangePrice;
  const sortBy = useMemo(
    () => Number(searchParams.get("sortBy")),
    [searchParams]
  );

  //
  //   "filters",
  //   filter,
  //   isChecked,
  //   selectedBrands,
  //   rangePrice,
  //   isRangePrice,
  //   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 pathname = usePathname();
  const router = useRouter();
  const handleInfiniteNextFetchProducts = () => {
    // Increment the page number
    const nextPage = pageGetProducts + 1;

    const params = new URLSearchParams(searchParams.toString());
    params.set("page", nextPage);
    router.push(`${pathname}?${params}`, { scroll: false });

    // 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(() => {
    setLoading(false);
    getData();
  }, []);

  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 />
    </>
  );
}
