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';

const baseUrl = 'https://api.jazzagain.com/public/index.php'

interface SellerProps {
    sellerId: string
}

const MoreFromSeller: React.FC<SellerProps> = ({ sellerId }) => {

    const router = useRouter();

    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 getMoreFromSeller = async () => {
        const res = await fetchDataWithCache(`${baseUrl}/api/moreBySeller/${sellerId}`)
        const otherProducts = res.data.filter((i: any) => {
            return i._id != router.query.id
        })
        setData(otherProducts)
    }

    useEffect(() => {
        if (sellerId) {
            getMoreFromSeller();
        }
        return () => { }
    }, [])

    if (data.length === 0) {
        return (
            <div className='text-center m-12'>
                <p className='p-4'>No more products found from this seller !</p>
                <Link href='/' className='p-2 bg-black rounded text-white'>Browse more</Link>
            </div>

        )
    }

    return (
        <>
            <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-t-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>
                            </div>
                            <FavoritesIcon itemId={item?._id} />
                        </div>
                    </div>
                ))}
            </div>
        </>
    )
}

export default MoreFromSeller