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 Cookies from "js-cookie";
import { useRouter } from "next/router";
import toast, { Toaster } from "react-hot-toast";
import { Skeleton } from "antd";
import { useSelector } from "react-redux";
import { RootState } from "@/Redux/store";

type featuredDataProps = {
  imgUrl: string;
  price: number;
  name: string;
  category: string;
};

type SizeType = 'default' | 'small' | 'large';

const FeaturedCards: React.FC = () => {
  const router = useRouter();
  const AllProducts = useSelector((state: RootState) => state.productFilter);
  const [data, setData] = useState<any[]>([]);
  const [sellersData, setSellersData] = useState<any[]>([])
  const [active, setActive] = useState(false);
  const [block, setBlock] = useState(false);
  const [size, setSize] = useState<SizeType>('large');

  const LoadingImages = [0, 1, 2, 3, 4, 5, 6, 7]

  React.useEffect(() => {
    const getFeaturedData = async () => {
      try {
        const response = await axios.get(
          "https://api.jazzagain.com/public/index.php/api/getFeaturedProducts"
        );
        // Handle the response
        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);
      }
    };
    getFeaturedData();
  }, []);

  const successNotify = () => toast.success("Added Successfully !");
  const errorNotify = (msg: string) =>
    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(error.response.data.message);
        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 FeaturedCards;
