import axios from "axios";
import React, { useEffect, useState } from "react";
// import { AiOutlineHeart } from "react-icons/ai";
import styles from "@/styles/common/small.module.css";
import { useRouter } from "next/router";
import FavoritesIcon from "../helpers/FavoritesIcon";
// import Link from "next/link";
import { formatNumberWithCommas } from "../commonFunctions/formatNumberWithCommas";
import { userActivity } from "../commonFunctions/userActivity";
import { useSelector } from "react-redux";
import { RootState } from "@/Redux/store";


interface NatureProps {
  nature: {
    categoryId: string;
    subcategoryId: string;
  };
}

const SimilarProducts: React.FC<NatureProps> = ({ nature }) => {
  const router = useRouter();

  const { categoryId, subcategoryId } = nature;

  const [data, setData] = useState([]);

  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  async function fetchDataWithCache(endpoint: string) {
    const cacheKey = `cache_${endpoint}`;
    const cached = localStorage.getItem(cacheKey);

    const axiosInstance = axios.create({
      baseURL: "https://api.jazzagain.com/public/index.php",
    });

    if (cached) {
      const { data, timestamp } = JSON.parse(cached);
      const isFresh = Date.now() - timestamp < 120000;

      if (isFresh) {
        return data;
      }
    }

    // If data is not in cache or is stale, fetch from API
    try {
      const response = await axiosInstance.get(endpoint);
      const data = response;
      // Cache the new data along with the current timestamp
      localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: Date.now() }));
      return data;
    } catch (error) {
      throw error;
    }
  }

  const getSimilar = async () => {
    // const res = await axios.get(
    //   `${baseUrl}/api/getProducts?categoryId=${categoryId}&subCategoryId=${subcategoryId}`
    // );
    const res = await fetchDataWithCache(
      `/api/getProducts?categoryId=${categoryId}&subCategoryId=${subcategoryId}`
    );

    const otherProducts = res.data.products.data.filter((i: any) => {
      return i._id != router.query.id;
    });

    setData(otherProducts);
  };

  useEffect(() => {
    if (categoryId && subcategoryId) {
      getSimilar();
    }
    return () => { };
  }, []);

  if (data.length === 0) {
    return null;
  }
  return (
    <>
      <hr className="border border-gray-300 w-[90%] mx-auto sm:my-6 my-[1rem]" />

      <div className="flex justify-between mt-[1rem]">
        <h2 className="text-[#FF332B] text-base">Similar Products</h2>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 justify-center">
        {data.map((item: any, index: number) => (
          <div
            key={index}
            className="w-[95%] grid mx-auto m-[1rem] cursor-pointer"
            onClick={() => {

              router.push(`/singleproduct/${item._id}`)
            }
            }
          >
            <div
              style={{
                backgroundImage: `url(https://api.jazzagain.com/public/${item.productFeaturedImage})`,
              }}
              className={`relative w-[100%] aspect-[2/1.3] rounded-md bg-cover bg-center bg-no-repeat flex flex-row-reverse`}
            >
              <div
                className={"w-20 h-6 bg-[#FF332B] text-white flex items-center justify-center ".concat(
                  styles.borderRounded
                )}
              >
                &#8358; {formatNumberWithCommas(item.productSellingPrice)}
              </div>
              {(item?.negotiable === true || item?.negotiable === 'true') && (
                <div className="flex justify-end absolute bottom-0 right-0">
                  <span className="bg-[#FE342B] text-white text-[10px] px-2 py-[2px] rounded-b-md">
                    Price Negotiable
                  </span>
                </div>
              )}
            </div>
            <div className="flex justify-between items-center">
              <div className="m-1">
                <p> {item.productTitle.length > 20 ? `${item.productTitle.slice(0, 20)}...` : item.productTitle}</p>
                <p className="text-xs text-gray-600">
                  {item.productDiscountPercentage} % Discount
                </p>
                <p className="text-xs text-gray-600 mt-1">
                  Location - {item?.seller?.city?.name}, {item?.seller?.state?.name}
                </p>
              </div>
              <FavoritesIcon itemId={item?._id} />
            </div>
          </div>
        ))}
      </div>
    </>
  );
};

export default SimilarProducts;
