import React, { useEffect, useState } from "react";
import ProductCard from "../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 "./relatedProduct.module.css";
import { ArrowBackIos, ArrowForwardIos } from "@mui/icons-material";
import Image from "next/image";
import { customerApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import { useRouter } from "next/router";

const RelatedProduct = (props) => {
  const [loader, setLoader] = useState(true);
  const router = useRouter();
  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 = JSON.stringify({
      "category.category": { $all: [...props.id] },
      stock: { $gt: 0 },
    });
    await customerApi
      .get("/products?limit=30&page=1&params=" + params + "&noVariant=false")
      .then((res) => {
        setLoader(false);
        setProductData(() => {
          let newArray = { ...res.data.result };
          newArray.data = newArray.data.filter(
            (item) => item.slug != router.query.id
          );
          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;
                }
              }
            }
            item["brand"] = item.category[item.category.length - 1].name;
          }
          return newArray;
        });
      })
      .catch((err) => {
        setLoader(false);
        router.push("/store");
        console.log(err);
      });
  };

  useEffect(() => {
    if (props.id && props.id.length > 0) {
      loadStoreData();
    }
  }, [props.id]);

  return (
    <React.Fragment>
      <div className={style.related_product_section}>
        {productData.data.length > 0 && (
          <div className={style.related_head}>
            <div className={style.heading}>Related Products</div>
            <div className={style.arrow_nav}>
              {productData.length > 5 * 1 && (
                <>
                  <BackBtn />
                  <ForwardBtn />
                </>
              )}
            </div>
          </div>
        )}
        {loader && <Loader className={style.loader} />}
        {!loader && (
          <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}>
                <ProductCard
                  name={item.name}
                  price_type={item.price_type}
                  price={item.price}
                  qty={item.stock}
                  slug={item.slug}
                  offer={item.offer}
                  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}
                />
              </SwiperSlide>
            ))}
          </Swiper>
        )}
      </div>
    </React.Fragment>
  );
};

export default RelatedProduct;
