import React, { useState } from "react";
import Link from "next/link";
import { AiOutlineHeart } from "react-icons/ai";
import styles from "@/styles/common/small.module.css";
import axios from "axios";
import { useRouter } from "next/router";
import Cookies from "js-cookie";
import FavoritesIcon from "../helpers/FavoritesIcon";
import toast, { Toaster } from "react-hot-toast";
import { Skeleton } from "antd";
import { useDispatch, useSelector } from "react-redux";
import {
  setFilteredProducts,
  setPagination,
  setProducts,
} from "@/Redux/productFiltersSlice";
import { formatNumberWithCommas } from "../commonFunctions/formatNumberWithCommas";
import { useQuery } from "react-query";
import { RootState } from "@/Redux/store";
import { userActivity } from "../commonFunctions/userActivity";
import { FaRegEye } from "react-icons/fa";

const LoadingImages = [0, 1, 2, 3, 4];

const RecomandedProducts: React.FC = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  // const [viewCounts, setViewCounts] = useState<Record<string, number>>({}); // Store view counts

  // const fetchData = async () => {
  //   const cacheKey = 'cache_/recommendedProducts';
  //   const cachedData = localStorage.getItem(cacheKey);

  //   // Try to parse cached data
  //   let cached;
  //   if (cachedData) {
  //     try {
  //       cached = JSON.parse(cachedData);
  //     } catch (error) {
  //       console.error("Error parsing cached data:", error);
  //     }
  //   }

  //   // Check if cached data is fresh
  //   if (cached && Date.now() - cached.timestamp < 120000) { // 1 hour freshness
  //     console.log('Returning data from localStorage');
  //     return cached.data; // Return cached data if it's fresh
  //   }

  //   try {
  //     // Make the API call if data is not in cache or is stale
  //     const response = await axios.get(
  //       "https://api.jazzagain.com/public/index.php/api/getRecomendedProducts"
  //     );
  //       console.log("recomm-feat.response.data",response.data)
  //     // Extract data from the response
  //     const productsData = response.data.products.data;

  //     // Cache the new data along with the current timestamp
  //     localStorage.setItem(cacheKey, JSON.stringify({ data: { products: productsData }, timestamp: Date.now() }));

  //     return { products: productsData };
  //   } catch (error) {
  //     console.error("Error:", error);
  //     throw new Error('Failed to fetch data');
  //   }
  // };

  const fetchData = async () => {
    const cacheKey = "cache_/recommendedProducts";
    const cachedData = localStorage.getItem(cacheKey);

    // Try to parse cached data
    let cached;
    if (cachedData) {
      try {
        cached = JSON.parse(cachedData);
      } catch (error) {
        console.error("Error parsing cached data:", error);
      }
    }

    // Check if cached data is fresh
    if (cached && Date.now() - cached.timestamp < 120000) {
      // console.log('Returning data from localStorage');
      return cached.data; // Return cached data if it's fresh
    }

    try {
      let allProducts: any[] = [];
      let currentPage = 1;
      let lastPage = 0;

      do {
        // Make the API call if data is not in cache or is stale
        const response = await axios.get(
          `https://api.jazzagain.com/public/index.php/api/getRecomendedProducts?page=${currentPage}`
        );

        // Extract data from the response
        const productsData = response.data.products;
        allProducts = allProducts.concat(productsData.data); // Concatenate the current page's products to the allProducts array

        currentPage = productsData.current_page + 1;
        lastPage = productsData.last_page;
      } while (currentPage <= lastPage);

      // Cache the new data along with the current timestamp
      localStorage.setItem(
        cacheKey,
        JSON.stringify({
          data: { products: allProducts },
          timestamp: Date.now(),
        })
      );

      return { products: allProducts };
    } catch (error) {
      console.error("Error:", error);
      throw new Error("Failed to fetch data");
    }
  };

  // const fetchViewCount = async (productId: string) => {
  //   try {
  //     console.log(`Fetching view count for productId: ${productId}`);
  //
  //     const response = await axios.post(
  //       `https://api.jazzagain.com/public/index.php/api/productViewsCount`,
  //       { productId }
  //     );
  //     console.log("id" ,productId)
  //
  //     console.log("View count response:", response.data);
  //
  //     return response.data.ViewCount || 0;
  //   } catch (error) {
  //     console.error("Error fetching view count:", error);
  //     return 0;
  //   }
  // };

  // const getFeaturedData = async () => {
  //   try {
  //     const response = await axios.get(
  //       "https://api.jazzagain.com/public/index.php/api/getRecomendedProducts"
  //     );
  //     const products = response.data.products.data;
  //     // setData(response.data.products.data);
  //     return {
  //       products:products
  //     }
  //     // console.warn("Response:", response.data.products.data);
  //   } catch (error) {
  //     console.error("Error:", error);
  //   }
  // };

  const { data, isLoading, isError } = useQuery("recommendedData", fetchData, {
    staleTime: 1000 * 60 * 60 * 2,
  });

  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  const viewAllHandler = async () => {
    // Check if all products are already fetched and stored in Redux or local storage
    const allProductsCached = localStorage.getItem("cache_/featuredProducts");
    userActivity(
      _loggedIn_user?._id,
      "website",
      "Recommended products  ",
      {
        pageVisit: `/`,
      },
      navigator.userAgent
    );
    if (!allProductsCached) {
      // Fetch all products only if not already fetched
      try {
        let allProducts: any[] = [];
        let currentPage = 1;
        let lastPage = 0;

        do {
          const response = await axios.get(
            `https://api.jazzagain.com/public/index.php/api/getFeaturedProducts?page=${currentPage}`
          );
          const productsData = response.data;
          allProducts = allProducts.concat(productsData.data);

          currentPage = productsData.current_page + 1;
          lastPage = productsData.last_page;
        } while (currentPage <= lastPage);

        // Assuming setFilteredProducts and setProducts actions expect an array of products
        dispatch(setFilteredProducts(allProducts));
        dispatch(setProducts(allProducts));
        dispatch(setPagination({}));
      } catch (error) {
        console.error("Error fetching all products:", error);
      }
    } else {
      const allProducts = data?.products;
      dispatch(setFilteredProducts(allProducts));
      dispatch(setProducts(allProducts));
      dispatch(setPagination({}));
    }
    router.push("/product/recommended");
  };

  return (
    <>
      <div className="flex justify-between px-2 py-1 rounded bg-[#383736] mb-4">
        <Toaster
          toastOptions={{
            className: "",
            duration: 5000,
          }}
        />
        <h2 className="text-[#fff] text-xl font-semibold tracking-wide">
          Recommended Products
        </h2>
        {/* <div
          onClick={()=>{
            dispatch(setFilteredProducts(data?.products))
            dispatch(setProducts(data?.products))
            router.push('/product/recommended')
          }}
          className="text-white hover:underline transition-all duration-300 cursor-pointer"
        >
          View All
        </div> */}
        <div
          onClick={viewAllHandler}
          className="text-white hover:underline transition-all duration-300 cursor-pointer"
        >
          View All
        </div>
      </div>
      {/* Recommended products */}
      <div className="grid gap-2 bg-[#FAF0E4] grid-cols-2 text-xs sm:text-sm sm:grid-cols-3 lg:grid-cols-5 justify-center">
        {data?.products.length > 0 ? (
          data?.products.slice(0, 12).map((item: any, index: number) => (
            <div
              onClick={() => router.push(`/singleproduct/${item._id}`)}
              key={index}
              className="w-full p-2 cursor-pointer"
            >
              <div
                style={{
                  backgroundImage: `url(https://api.jazzagain.com/public/${item.productFeaturedImage})`,
                }}
                className="w-full aspect-[2/1.7] rounded-md bg-cover bg-center bg-no-repeat flex flex-col justify-between"
              >
                {/* 🔼 Top Row: Price and View Count */}
                <div className="flex justify-between">
                  {/* Price Box */}
                  <div
                    className={"h-6 p-1 bg-[#FE342B] text-white flex items-center justify-center ".concat(
                      styles.borderRounded
                    )}
                  >
                    <span className="flex">
                      <span className="px-1">&#8358;</span>
                      <span>
                        {formatNumberWithCommas(item.productSellingPrice)}
                      </span>
                    </span>
                    <span className="flex pl-1 text-xs">
                      <span>-</span>
                      <span>{item.productDiscountPercentage}</span>
                      <span>%</span>
                    </span>
                  </div>

                  {/* View Count */}
                  <div className="flex gap-1 items-center h-6 px-2 rounded-b-md bg-[#FE342B] text-white text-sm">
                    <FaRegEye size={16} />
                    <span>{item.viewsCount || 0}</span>
                  </div>
                </div>
                {(item?.negotiable === true || item?.negotiable === 'true') && (
                  <div className="flex justify-end ">
                    <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 font-semibold">
                <div className="m-1">
                  <p>{item.productTitle}</p>
                  <p className="text-xs text-gray-600">
                    Location - {item.seller?.city?.name},{" "}
                    {item.seller?.state?.name}
                  </p>
                </div>

                <div className="flex flex-col  items-end mr-1">
                  {/* Favorite Icon */}
                  <FavoritesIcon itemId={item._id} />
                </div>
              </div>
            </div>
          ))
        ) : (
          <>
            {LoadingImages.map((i) => {
              return (
                <div className="m-3" key={i}>
                  <div
                    className={`w-44 h-44 md:w-64 md:h-64 sm:h-36 bg-gradient-to-br from-gray-200 via-gray-300 to-gray-200 animate-pulse`}
                  ></div>
                  <Skeleton.Input
                    active
                    size="small"
                    className="my-2 w-44! md:w-64!"
                  />
                </div>
              );
            })}
          </>
        )}
      </div>
    </>
  );
};

export default RecomandedProducts;
