import React 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, setProducts } from "@/Redux/productFiltersSlice";
import { RootState } from "@/Redux/store";

type recomandedDataProps = {
    imgUrl: string;
    price: number;
    name: string;
    category: string;
};

const LoadingImages = [0, 1, 2, 3, 4];

const RecommendedCards: React.FC = () => {
    const router = useRouter();
    const AllProducts = useSelector((state: RootState) => state.productFilter);

    const [data, setData] = React.useState<any[]>([]);
    const [sellersData, setSellersData] = React.useState<any[]>([]);

    React.useEffect(() => {
        const getRecomendedData = async () => {
            try {
                const response = await axios.get(
                    "https://api.jazzagain.com/public/index.php/api/getRecomendedProducts"
                );
                setData(response.data.products.data);
                console.warn("Response:", response.data.products.data);
                const sellers = await axios.get(
                    "https://api.jazzagain.com/public/index.php/api/getSellers"
                );
                setSellersData(sellers.data.sellers);
            } catch (error) {
                console.error("Error:", error);
            }
        };
        getRecomendedData();
    }, []);

    const successNotify = () => toast.success("Added Successfully !");
    const errorNotify = () =>
        toast.error("You are not logged in, Please login first.");

    const handleFavoriteClick = (itemId: string) => (event: any) => {
        event.stopPropagation();

        const authToken = Cookies.get("jazz_token");

        const config = {
            headers: {
                authorization: `Bearer ${authToken}`,
            },
        };

        const data = {
            productId: itemId,
        };

        axios
            .post(
                "https://api.jazzagain.com/public/index.php/api/user/saveFavourite",
                data,
                config
            )
            .then((response) => {
                if (response) successNotify();
            })
            .catch((error) => {
                errorNotify();
                router.push("/auth/login");
            });
    };

    const getSellerAddress = (id: string) => {
        const findAddress = sellersData.find((data) => data._id === id);

        if (!findAddress) {
            return (
                <p className="text-xs text-gray-600">Location - Address not found</p>
            );
        }

        const city = findAddress.city?.name || "Unknown City";
        const state = findAddress.state?.name || "Unknown State";

        return (
            <p className="text-xs text-gray-600">
                Location - {city}, {state}
            </p>
        );
    };

    const handleItemClick = (itemId: string) => {
        router.push(`/singleproduct/${itemId}`);
    };

    return (
        <>

            <div className="grid grid-cols-2 bg-[#E5E4E5] text-xs sm:text-base sm:grid-cols-2 lg:grid-cols-3 justify-center">
                <Toaster
                    toastOptions={{
                        className: "",
                        duration: 5000,
                    }}
                />
                {AllProducts.filteredProducts.length === 0 ? (
                    <div className="grid col-span-3 text-center">
                        <h2 className="mt-2 text-lg font-semibold px-3 text-gray-800">
                            No Product Found
                        </h2>
                        <p className="mt-1 text-gray-600 px-3">
                            Sorry, we couldn&apos;t find any products that match your search.
                        </p>
                    </div>
                ) : (
                    AllProducts.filteredProducts.map((item: any, index: number) => (

                        <div
                            key={index}
                            className="w-[95%] mx-auto m-[.5rem] cursor-pointer"
                            onClick={() => handleItemClick(item._id)}
                        >
                            <div
                                style={{
                                    backgroundImage: `url(https://api.jazzagain.com/public/${item.productFeaturedImage})`,
                                }}
                                className={` w-[100%] aspect-[2/1.2] rounded-md bg-cover bg-center bg-no-repeat flex flex-row-reverse`}
                            >
                                <div
                                    className={"sm:w-20 w-[70px] h-7 sm:h-9 bg-[#FF332B] text-xs sm:text-base text-white flex items-center justify-center ".concat(
                                        styles.borderRounded
                                    )}
                                >
                                    &#8358; {item.productSellingPrice}
                                </div>
                            </div>
                            <div className="flex justify-between">
                                <div className="m-1 font-semibold">
                                    <p>{item.productTitle}</p>
                                    {getSellerAddress(item.userId)}
                                    {/* <p className="text-xs text-gray-600">{item.category}</p> */}
                                    {/* <p className="text-xs text-gray-600">Location - Ikeja, Lagos</p> */}
                                </div>
                                <div className="h-8 w-8 my-1">
                                    <AiOutlineHeart
                                        size={30}
                                        // className="text-[#FF332B] cursor-pointer hover:scale-[1.2]"
                                        // className={}
                                        onClick={(e:any) => {
                                            e.stopPropagation();
                                            handleFavoriteClick(item._id);
                                        }}
                                    />
                                </div>
                                {/* <FavoritesIcon itemId={item._id}/> */}
                            </div>
                        </div>
                    ))
                )}
            </div>
        </>
    );
};

export default RecommendedCards;
