import React, { useEffect, useState } from "react";
import style from "./productSection.module.css";
import ProductCard from "@/components/productList/product_card";
import { useWindowSize } from "../../customHook/useWindowSize";
import Pagination from "@/components/utils/pagination";
import Loader from "../utils/btnLoader";
import { useRouter } from "next/router";
import { customerApi } from "../../api/api";
import { useDispatch } from "react-redux";

const ProductSection = () => {
  const [loader, setLoader] = useState(false);
  const [page, setPage] = useState(1);
  const [storeData, setStoreData] = useState([]);
  const router = useRouter();
  const { query } = router;
  const [id, setID] = useState(null);
  const [tableData, setTableData] = useState({});

  const dispatch = useDispatch();

  const loadStoreData = async (pageNo) => {
    setLoader(true);
    setTableData([]);
    let params = JSON.stringify({ stock: { $gt: 0 } });
    await customerApi
      .get(
        "/products?limit=40&page=" +
          pageNo +
          "&params=" +
          params +
          "&noVariant=false"
      )
      .then((res) => {
        setLoader(false);
        setTableData(res.data.result);
        setStoreData((prev) => {
          let newArray = [...prev];
          let inputData = res.data.result.data;
          newArray.push(...inputData);
          return newArray;
        });
      })
      .catch((err) => {
        setLoader(false);
        console.log(err);
      });
  };

  useEffect(() => {
    setPage(1);
    loadStoreData(1);
  }, []);

  const { width } = useWindowSize();

  return (
    <React.Fragment>
      <div className={style.section}>
        <div className={`primary-heading ${style.heading}`}>More To Love</div>
        <div className={style.store_grid}>
          {storeData && storeData && storeData.length > 0 && (
            <>
              <div className={style.product_section}>
                <div className={style.grid}>
                  {storeData.map((item) => (
                    <ProductCard
                      name={item.name}
                      price_type={item.price_type}
                      price={item.price}
                      qty={item.stock}
                      offer={item.offer}
                      slug={item.slug}
                      id={item._id}
                      partNo={item.partNo}
                      tax={item.tax_rate}
                      image={
                        item.cover_image
                          ? process.env.NEXT_PUBLIC_UPLOADS +
                            "/products/" +
                            item.cover_image
                          : item.image &&
                            process.env.NEXT_PUBLIC_UPLOADS +
                              "/products/" +
                              item.image[0]
                      }
                      brand={item.brand}
                      key={item.name}
                      payment_accepted={item.payment_accepted}
                      other_category={item.other_category}
                      category_group={item.category_group}
                    />
                  ))}
                  {storeData.length % 5 !== 0 && (
                    <>
                      {!loader && tableData.pageCount > page && (
                        <div className={style.btnSection}>
                          <div
                            className={`teritary_btn ${style.load_more_btn}`}
                            onClick={() => {
                              setPage(page + 1);
                              loadStoreData(page + 1);
                            }}
                          >
                            Load More
                          </div>
                        </div>
                      )}
                      {loader && (
                        <div className={style.btnSection}>
                          <div
                            className={`teritary_btn ${style.load_more_btn}`}
                          >
                            <Loader className={style.loader} />
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
        {storeData.length % 5 === 0 && (
          <>
            {!loader && tableData.pageCount > page && (
              <div className={style.btnSection}>
                <div
                  className={`teritary_btn ${style.load_more_btn}`}
                  onClick={() => {
                    setPage(page + 1);
                    loadStoreData(page + 1);
                  }}
                >
                  Load More
                </div>
              </div>
            )}
            {loader && (
              <div className={style.btnSection}>
                <div className={`teritary_btn ${style.load_more_btn}`}>
                  <Loader className={style.loader} />
                </div>
              </div>
            )}
          </>
        )}

        {/* <Pagination
          totalData={storeData.total}
          totalDataPerPage={12}
          totalNumberToDisplay={5}
          page={page}
          getPage={(value) => {
            setPage(value);
            loadStoreData(value);
          }}
        /> */}
        {!loader && (!storeData || storeData.length === 0) && (
          <div className={style.emptyClass}>
            <p className={`exist_error ${style.exist_error}`}>Empty Store</p>
          </div>
        )}
      </div>
    </React.Fragment>
  );
};

export default ProductSection;
