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 {
  console.log("Endpoint:", endpoint);

  const response = await axiosInstance.get(endpoint);

  const data = response.data;

  localStorage.setItem(
    cacheKey,
    JSON.stringify({
      data,
      timestamp: Date.now(),
    })
  );

  return data;

} catch (error) {
  console.error("Error fetching data:", 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 products = res?.products?.data || res?.products || [];

const otherProducts = products.filter((i: any) => {
  const id = i?.id || i?.id;
  return 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) => {
  const productId = item?.id || item?.id;

  if (!productId) return null;



  return (
    <div
      key={productId}
      className="w-[95%] grid mx-auto m-[1rem] cursor-pointer"
onClick={() => {
  const productId = item?.id || item?.id;

  if (!productId) {
    console.error("Product ID missing:", item);
    return;
  }

  router.push(`/singleproduct/${productId}`);
}}    >
      <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 || item?.id} />      </div>
    </div>
  );
})}
      </div>
    </>
  );
};

export default SimilarProducts;
