import React, { useEffect, useState } from "react";
import ProductCard from "@/components/productList/product_card";
import { Swiper, SwiperSlide, useSwiper } from "swiper/react";
import { Grid, Navigation } from "swiper";
import "swiper/css";
import "swiper/css/grid";
import "swiper/css/pagination";

import style from "./productSlider.module.css";
import { ArrowBackIos, ArrowForwardIos } from "@mui/icons-material";
import { customerApi } from "@/api/api";
import Loader from "@/components/utils/loader";

const ProductSlider = (props) => {
  const [loader, setLoader] = useState(true);
  const [productData, setProductData] = useState({ data: [] });
  const [randomID] = useState("id_" + Math.floor(Math.random() * 1000000 + 1));
  const ForwardBtn = () => {
    return (
      <ArrowForwardIos
        className={`swiper-button-next-${randomID} ${style.btn_next}`}
      />
    );
  };
  const BackBtn = () => {
    return (
      <ArrowBackIos
        className={`swiper-button-prev-${randomID} ${style.btn_prev}`}
      />
    );
  };
  const loadStoreData = async () => {
    setLoader(true);
    const params = props.id
      ? JSON.stringify({
          $or: [
            { other_category: props.id },
            { "category.category": props.id },
          ],
        })
      : JSON.stringify({});
    const count = props.count ? props.count : 30;
    await customerApi
      .get(
        "/products?limit=" +
          count +
          "&page=1&params=" +
          params +
          "&noVariant=true"
      )
      .then((res) => {
        console.log("productlist", res.data);
        setLoader(false);
        setProductData(() => {
          let newArray = { ...res.data.result };
          for (const item of newArray.data) {
            if (item.details.length > 0) {
              for (const innerItem of item.details) {
                if (innerItem.title.toLowerCase() === "part no") {
                  item["partNo"] = innerItem.value;
                }
              }
            }
          }
          return newArray;
        });
      })
      .catch((err) => {
        setLoader(false);
        console.log(err);
      });
  };

  useEffect(() => {
    loadStoreData();
    console.log("yes");
  }, []);

  return (
    <React.Fragment>
      {(loader || productData.data.length > 0) && (
        <div className={`${style.product_section} container`}>
          {loader && <Loader className={style.loader} />}
          {!loader && productData.data.length > 0 && (
            <>
              <div className={style.product_head}>
                {props.title && (
                  <div className="primary-heading">{props.title}</div>
                )}
                {productData.data.length > 0 &&
                  productData.data.length > props.singleCount && (
                    <div className={style.arrow_nav}>
                      <BackBtn />
                      <ForwardBtn />
                    </div>
                  )}
              </div>
              <Swiper
                grid={{
                  fill: "row",
                }}
                breakpoints={{
                  1199: {
                    slidesPerView: props.singleCount
                      ? Number(props.singleCount)
                      : 5,
                    grid: { rows: 1 },
                  },
                  991: {
                    slidesPerView: 4,
                    grid: { rows: 1 },
                  },
                  768: {
                    slidesPerView: 3,
                    grid: { rows: 1 },
                  },
                  350: { slidesPerView: 2, grid: { rows: 1 } },
                  0: { slidesPerView: 1, grid: { rows: 1 } },
                }}
                spaceBetween={20}
                modules={[Grid, Navigation]}
                className={style.mySwiper}
                navigation={{
                  nextEl: ".swiper-button-next-" + randomID,
                  prevEl: ".swiper-button-prev-" + randomID,
                }}
              >
                {productData.data.map((item, index) => (
                  <SwiperSlide className={style["swiper_slide"]} key={index}>
                    <div className={style.product_card_section}>
                      <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}
                      />
                    </div>
                  </SwiperSlide>
                ))}
              </Swiper>
            </>
          )}
          {/* {!loader && productData.data.length == 0 && (
          <p className={style.error}>No Product Available</p>
        )} */}
        </div>
      )}
    </React.Fragment>
  );
};

export default ProductSlider;
