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

const BlogPostSlider = (props) => {
  const [loader, setLoader] = useState(true);
  const [posts, setPosts] = useState({ data: [] });
  const [randomID] = useState("id_" + Math.floor(Math.random() * 1000000 + 1));
  const [productCheck, setPostCheck] = useState(null);
  const router = useRouter();
  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);
    await customerApi
      .get("/blog/posts?limit=" + props.count)
      .then((res) => {
        setLoader(false);
        if (res.data.result.data.length <= 0) {
          setPostCheck(false);
        } else {
          setPostCheck(true);
        }
        setPosts(() => {
          let newArray = { ...res.data.result };
          return newArray;
        });
      })
      .catch((err) => {
        setLoader(false);
        console.log(err);
      });
  };

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

  return (
    <React.Fragment>
      {productCheck === true && (
        <div className={style.product_section}>
          <div className={style.product_head}>
            {props.title && (
              <div className="primary-heading">{props.title}</div>
            )}
            {posts.data.length > 0 && posts.data.length > props.singleCount && (
              <div className={style.arrow_nav}>
                <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,
                }}
              >
                {posts.data.map((item, index) => (
                  <SwiperSlide className={style["swiper_slide"]} key={index}>
                    <div
                      className={style.post_card_section}
                      onClick={() =>
                        router.push(`/blog/${item._id}_${item.title}`)
                      }
                    >
                      <div className={style.image_section}>
                        <NextImage
                          src={
                            process.env.NEXT_PUBLIC_UPLOADS +
                            "/blogs/" +
                            item.normal_image
                          }
                          fill
                        />
                      </div>
                      <div className={style.date}>
                        {moment(item.created_at).format("DD MMM YYYY")}
                      </div>
                      <div className={style.title}>{item.title}</div>
                    </div>
                  </SwiperSlide>
                ))}
              </Swiper>
              {posts.data.length > 0 && props.count < posts.data.length && (
                <div className={style.btn_section}>
                  <button
                    className={`secondary-btn`}
                    type="button"
                    onClick={() => router.push("/blog")}
                  >
                    View More
                  </button>
                </div>
              )}
            </>
          )}
          {!loader && posts.data.length == 0 && (
            <p className={style.error}>No Post Available</p>
          )}
        </div>
      )}
    </React.Fragment>
  );
};

export default BlogPostSlider;
