

import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import React, { useEffect } from "react";
import Slider from "react-slick";
import Image from "next/image";
import { useState } from "react";
import axios from "axios";
import { useRouter } from "next/router";
import Link from "next/link";
import { useDispatch, useSelector } from "react-redux";
import { setFilteredProducts, setProducts } from "@/Redux/productFiltersSlice";
import toast from "react-hot-toast";
import { userActivity } from "../commonFunctions/userActivity";
import { RootState } from "@/Redux/store";

function SampleNextArrow(props: any) {
  const { className, style, onClick } = props;
  return (
    <div
      className={className}
      style={{
        ...style,
        borderRadius: "50%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: "#999",
        margin: "0 .5rem 0 0",
        zIndex: 20,
        padding: "20px",
      }}
      onClick={onClick}
    />
  );
}

function SamplePrevArrow(props: any) {
  const { className, style, onClick } = props;
  return (
    <div
      className={className}
      style={{
        ...style,
        borderRadius: "50%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: "#999",
        margin: "0 0 0 0.5rem",
        zIndex: 20,
        padding: "20px",
      }}
      onClick={onClick}
    />
  );
}

var settings = {
  dots: false,
  infinite: false,
  speed: 500,
  slidesToShow: 5,
  slidesToScroll: 5,
  initialSlide: 0,
  nextArrow: <SampleNextArrow />,
  prevArrow: <SamplePrevArrow />,
  responsive: [
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: true,
        dots: false,
      },
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2,
        initialSlide: 2,
      },
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1,
      },
    },
  ],
};

export default function NewlyAddedProducts() {
  const router = useRouter();
  const dispatch = useDispatch();

  const [latestProducts, setLatestProducts] = useState<any>([]);

  // useEffect(() => {
  //   axios
  //     .get("https://api.jazzagain.com/public/index.php/api/getLatestProducts")
  //     .then((response) => {
  //       setLatestProducts(response.data.products.data);
  //     })
  //     .catch((err) => {
  //       return toast.error("Error in fetching Newly Added Products");
  //     });
  // }, []);


    useEffect(() => {
      const cacheKey = 'cache_/latestProducts';
      const cachedData = localStorage.getItem(cacheKey);
  
      if (cachedData) {
        const { data, timestamp } = JSON.parse(cachedData);
        // Check if the cached data is still fresh, e.g., less than 1 hour old
        if (Date.now() - timestamp < 120000) {
          console.log('Returning data from localStorage');
          setLatestProducts(data);
          return; // Skip the API call if cached data is used
        }
      }
  
      axios.get("https://api.jazzagain.com/public/index.php/api/getLatestProducts")
        .then((response) => {
          setLatestProducts(response.data.products.data);
          // Cache the new data along with the current timestamp
          localStorage.setItem(cacheKey, JSON.stringify({
            data: response.data.products.data,
            timestamp: Date.now()
          }));
        })
        .catch((err) => {
          console.error("Error in fetching Newly Added Products", err);
          toast.error("Error in fetching Newly Added Products");
        });
    }, []);
  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  return (
    <div className="w-[85%] mx-auto">
      <div className="flex justify-between">
        <h2 className="text-[#fff] text-xl py-1 font-semibold tracking-wide">
          Newly Added Products
        </h2>
        <div
          onClick={() => {
              userActivity(
                  _loggedIn_user?.id,
                  "website",
                  "Newly added products  ",
                  {
                    pageVisit: `/`,
                  },
                  navigator.userAgent
                );
            dispatch(setFilteredProducts(latestProducts));
            dispatch(setProducts(latestProducts));
            router.push("/product/latest");
          }}
          className="text-white hover:underline cursor-pointer"
        >
          View All
        </div>
      </div>
      <Slider {...settings} className="mt-3 pb-2">
        {latestProducts.length > 0 ? (
          latestProducts.map((item: any, index: number) => (
            // <div key={index} className="cursor-pointer px-1">
            //   <div className="border border-white rounded-lg p-2">
            //     <div className="bg-gray-300 aspect-square"></div>

            //   </div>

            // </div>
           <div key={item?.id || item?.id} className="cursor-pointer">
              <div
                className="mx-1 rounded-md overflow-hidden relative"
                onClick={() => {
const productId = item?.id || item?.id;

if (!productId) {
  console.warn("Product ID missing:", item);
  return;
}

router.push(`/singleproduct/${productId}`);                }}
              >
                <Image
                  src={`https://api.jazzagain.com/public/${item.productFeaturedImage}`}
                  width={250}
                  height={250}
                  alt="featured product image"
                  className="object-contain bg-white aspect-[2/1.7] flex-1 mx-auto"
                />
                {(item?.negotiable === true || item?.negotiable === 'true') && (
                <div className="flex justify-end absolute right-0 bottom-0">
                  <span className="bg-[#FE342B] text-white text-[10px] px-2 py-[2px] rounded-b-md">
                    Price Negotiable
                  </span>
                </div>
              )}
              </div>
            </div>
          ))
        ) : (
          <p>Loading...</p>
        )}
      </Slider>
    </div>
  );
}
