
import React from "react";
import axios from "axios";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/Redux/store";
import { setCategory } from "@/Redux/userSelectionSlice";
import { useRouter } from "next/router";
import Image from "next/image";
import styles from "@/styles/common/catImg.module.css"
import { motion } from "framer-motion";
import { useQuery } from 'react-query';
import { setFilteredProducts, setPagination, setProducts } from "@/Redux/productFiltersSlice";
import { userActivity } from "../commonFunctions/userActivity";
import { ApiBaseUrl, ImagesBaseUrl } from "@/interceptor/instance";

// type DataProps = {
//   title: string;
//   logo: React.ReactNode;
//   bgcolor: string;
//   linkUrl: string;
// };

// const fetchData = async () => {
//   try {
//     // Make the first API call
//     const categoryResponse = await axios.get(
//       "https://api.jazzagain.com/public/index.php/api/getCategories"
//     );

//     // Extract data from the response
//     const categoriesData = categoryResponse.data.categories;


//     return {
//       categories: categoriesData,
//     };
//   } catch (error) {
//     console.error("Error:", error);
//   }
// };

const fetchData = async () => {
  const cacheKey = 'cache_/categoriesData';
  // Try to get cached data from localStorage
  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');
      return data; // Return cached data if it's fresh
    }
  }

  try {
    // Make the API call if no fresh data is in cache
    const categoryResponse = await axios.get(
      `${ApiBaseUrl}/api/getCategories`
    );

    // Extract data from the response
    const categoriesData = categoryResponse.data.categories;

    // Cache the new data along with the current timestamp
    localStorage.setItem(cacheKey, JSON.stringify({
      data: { categories: categoriesData },
      timestamp: Date.now()
    }));

    return {
      categories: categoriesData,
    };
  } catch (error) {
    console.log("Error fetching categories:", error);
    throw new Error('Failed to fetch categories');
  }
};


const CategorySection: React.FC = () => {
  const dispatch = useDispatch();
  const router = useRouter();

  const path = router.pathname;

  const selectedCategory = useSelector(
    (state: RootState) => state.category.selectedCategory
  );

  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  const [currentPage, setCurrentPage] = React.useState(1);

  const { data, isLoading, isError } = useQuery("categoryData", fetchData, {
    staleTime: 1000 * 60 * 60 * 2,
  });

  const handleCategoryClick = async(categoryName: string, categoryID: string) => {
    const stablePath = router.pathname;
    if (stablePath === "/sell") {
      userActivity(_loggedIn_user?._id,
        'website',
        'Sell',
        router.asPath,{
        pageVisit:'/sell'
      }, navigator.userAgent)
    } else {
      try {
        const response = await axios.get(
          `${ApiBaseUrl}/api/getProducts?categoryId=${categoryID}&page=${currentPage}`
        );
        dispatch(setProducts(response.data.products.data))
        dispatch(setFilteredProducts(response.data.products.data))
        dispatch(setPagination(response.data.products.pagination))
        userActivity(_loggedIn_user?._id,
          'website' ,
          'categories'
          ,router.asPath,{
          pageVisit:'/product'
        }, navigator.userAgent)
      } catch (error) {
        console.error("Error:", error);
      }
      router.push("/product");
    }
    dispatch(setCategory({ category: categoryName, categoryID: categoryID }));
  };

  return (
    <nav className="flex px-[.7rem] sm:px-1 sm:w-[70%] mx-auto py-2 flex-wrap">
      {data?.categories.map((item:any, index:number) => (
        <div 
          className={"bg-transparent m-1 p-1 sm:p-2 cursor-pointer flex items-center justify-center " .concat(styles.catImg)}
          onClick={() => handleCategoryClick(item.categoryName, item._id)}
          key={index}
        >
          <motion.div 
            className="flex flex-col items-center"
            whileHover={{scale:1.2,y:-5}}
            transition={{duration:0.2}}
          >
            <Image 
              src={`${ImagesBaseUrl}${item.categoryImage}`}
              alt="catagory indicator image"
              height={45}
              width={45}
            
            />

            <p
              className={`text-[11px] sm:text-xs ${
                item.categoryName === selectedCategory && path !== "/"
                  ? "font-semibold"
                  : ""
              }`}
            >
              {item.categoryName}
            </p>
          </motion.div>
        </div>
      ))}
    </nav>
  );
};

export default CategorySection;
