import React, { useEffect, useMemo, useRef, useState } from "react";
import style from "./index.module.css";
import ProductCard from "@/components/productList/product_card";
import ProductFilter from "@/components/productList/categories";
import OverlayBox from "../../components/utils/others/overlayBox";
import { useWindowSize } from "../../customHook/useWindowSize";
import { FilterAlt } from "@mui/icons-material";
import { carCatalogApi, customerApi } from "@/api/api";
import Pagination from "@/components/utils/pagination";
import Loader from "../../components/utils/btnLoader";
import { useRouter } from "next/router";
import Head from "next/head";
import Filters from "@/components/productList/filters";
import FadeInContainer from "@/components/utils/animation/fadeInContainer";

const ProductStore = (props) => {
  const [openFilter, setOpenFilter] = useState(false);
  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 [filterData, setFilterData] = useState();

  const loadStoreData = async (pageNo) => {
    setLoader(true);
    let params = "";
    if (id && id.length > 0) {
      params = {
        "category.category": { $all: id },
      };
    }
    if (filterData.priceRangeData)
      params = { ...params, ...filterData.priceRangeData };
    params = JSON.stringify(params);
    let sortData = JSON.stringify({});
    if (filterData.sortByData) {
      sortData = JSON.stringify(filterData.sortByData);
    }
    await customerApi
      .get(
        "/products?limit=40&page=" +
          pageNo +
          "&params=" +
          params +
          "&sort=" +
          sortData +
          "&noVariant=false"
      )
      .then((res) => {
        setLoader(false);
        console.log("data: ", storeData);
        setTableData(res.data.result);
        setStoreData((prev) => {
          let newArray = [...prev];
          let inputData = res.data.result.data;
          for (const item of inputData) {
            if (item.details.length > 0) {
              for (const innerItem of item.details) {
                if (innerItem.title.toLowerCase() === "part no") {
                  item["partNo"] = innerItem.value;
                }
              }
            }
            item["brand"] =
              item.category[item.category.length - 1] &&
              item.category[item.category.length - 1].name
                ? item.category[item.category.length - 1].name
                : "";
          }
          newArray.push(...inputData);
          return newArray;
        });
      })
      .catch((err) => {
        setLoader(false);
        console.log(err);
      });
  };

  useMemo(() => {
    if (query.slug) {
      const id = [];
      console.log("router.query: ", query);
      if (query.slug && query.slug.length > 0) {
        for (const item of query.slug) {
          if (item.includes("[")) {
            let data = item.split("[")[1];
            data = data.split("]")[0];
            id.push(data);
          } else {
            id.push(item);
          }
        }
        setID(id);
      }
    } else setID([]);
  }, [query]);

  useMemo(() => {
    if (query.slug) {
      if (query.slug && query.slug.length > 0) {
        console.log("query.slug: ", query.slug);
        for (const item of query.slug) {
          if (item.includes("car[")) {
            setCarBrand(item.split(" ")[1]);
            let data = item.split("[")[1];
            data = data.split("]")[0];
            setCarID(data);
          }
        }
      }
    }
  }, [query]);

  useMemo(() => {
    if (id !== null && filterData) {
      setPage(1);
      loadStoreData(1);
      setStoreData([]);
    }
  }, [filterData, id]);

  const { width } = useWindowSize();

  return (
    <React.Fragment>
      <Head>
        <title>
          {props.metaData && props.metaData.meta_title
            ? props.metaData.meta_title
            : "Store"}
        </title>
        <meta charset="UTF-8" />
        <meta
          name="description"
          content={props.metaData && props.metaData.meta_description}
        />
        <meta
          name="keywords"
          content={
            props.metaData &&
            props.metaData.meta_keywords &&
            props.metaData.meta_keywords.length > 0
              ? props.metaData.meta_keywords.join(",")
              : ""
          }
        />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>
      <div className="container mt-2">
        {/* <div className={style.breadcrumps}>{props.breadcumbs}</div> */}

        <div className={style.store_grid}>
          <div className={style.filter_section}>
            <div
              className={style.store_filter}
              onClick={() => {
                if (width <= 768) {
                  setOpenFilter((prev) => !prev);
                }
              }}
            >
              <div className={style.filter_title}>
                Filter {width <= 768 && <FilterAlt />}
              </div>
              <div className={style.filter_section}>
                {width > 768 && (
                  <>
                    <Filters
                      getFilterData={(data) => {
                        setFilterData(data);
                      }}
                    />
                    <ProductFilter />
                  </>
                )}
              </div>
            </div>

            {width < 768 && (
              <div className={`${openFilter ? style.open : style.close}`}>
                <OverlayBox
                  title="Filter"
                  close={() => setOpenFilter(false)}
                  open={true}
                >
                  <Filters
                    getFilterData={(data) => {
                      setFilterData(data);
                    }}
                  />
                  <ProductFilter />
                </OverlayBox>
              </div>
            )}
          </div>{" "}
          <FadeInContainer loadVisibile={true} delay={500}>
            {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>
                  {storeData.length % 5 === 0 && (
                    <>
                      {!loader && tableData.pageCount > page && (
                        <div className={style.btnSection}>
                          <div
                            className={`teritary_btn`}
                            onClick={() => {
                              setPage(page + 1);
                              loadStoreData(page + 1);
                            }}
                          >
                            Load More
                          </div>
                        </div>
                      )}
                      {loader && (
                        <div className={style.btnSection}>
                          <div className={`teritary_btn`}>
                            <Loader className={style.loader} />
                          </div>
                        </div>
                      )}
                    </>
                  )}

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

export default ProductStore;

export const getStaticPaths = async () => {
  return {
    paths: [],
    fallback: "blocking",
  };
};

export const getStaticProps = async (ctx) => {
  let metaData = {};
  await Promise.all([customerApi.get("/site/meta?path=/store")])
    .then((res) => {
      if (res[0] && res[0].data) metaData = res[0].data.data;
    })
    .catch((err) => {
      console.log("err:", err);
    });
  return {
    props: {
      metaData: metaData,
    },
    revalidate: 10,
  };
};
