"use client";

import React, { useEffect } from "react";
import "./Popular_Product.css";
import { getAllTimeFavsProducts } from "../../../features/products/productsSlice";
import { useDispatch, useSelector } from "react-redux";
import { encodeId } from "../../../utils/common";
import { useRouter } from "next/navigation";

import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper/modules";
import "swiper/css";
import Common_Heading_Holder from "../../common-components/common_heading_holder/Common_Heading_Holder";

const Popular_Product = () => {
  const navigate = useRouter();
  const dispatch = useDispatch();

  const PopulerProducts = useSelector((state) => state.product.allProductsFavs);

  useEffect(() => {
    dispatch(getAllTimeFavsProducts({}));
  }, [dispatch]);

  return (
    <section className="Popular_Product Explore_By_Categoryyy">
      <div className="header-wrapper">
        <Common_Heading_Holder
          headingText={"Popular Products"}
          subtext={"Explore our most popular product"}
        />
      </div>

      <div className="popular-product-slider">
        <Swiper
          modules={[Autoplay]}
          spaceBetween={15}
          slidesPerView={8}
          loop={true}
          autoplay={{
            delay: 2000,
            disableOnInteraction: false,
            pauseOnMouseEnter: true,
          }}
          speed={800}
          breakpoints={{
            0: {
              slidesPerView: 3,
              spaceBetween: 12,
            },
            576: {
              slidesPerView: 4,
              spaceBetween: 15,
            },
            768: {
              slidesPerView: 5,
              spaceBetween: 18,
            },
            992: {
              slidesPerView: 6,
              spaceBetween: 20,
            },
            1200: {
              slidesPerView: 8,
              spaceBetween: 20,
            },
          }}
        >
          {PopulerProducts?.map((item, index) => (
            <SwiperSlide key={item?.id || index}>
              <div
                className="popular-product-item"
                onClick={() =>
                  navigate.push(`/product-details/${encodeId(item?.id)}`)
                }
              >
                <div className="popular-image-wrapper">
                  <img
                    src={process.env.NEXT_PUBLIC_IMG_URL + item?.image}
                    className="popular-product-image"
                    alt={item?.name || "product"}
                  />
                </div>

                <p className="popular-product-name">{item?.name}</p>
              </div>
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
    </section>
  );
};

export default Popular_Product;
