"use client";

import { getToken } from "@/actions/cookies";
import addToCart from "@/api/cart/addToCart";
import postData from "@/api/post-data";
import { toastError, toastSuccess } from "@/services/custom-toast";
import useCart from "@/stores/cart";
import { useCurrency } from "@/stores/currency-state";
import useWishlistStore from "@/stores/wishlist";
import { Loader2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { useState } from "react";
import { CgShoppingCart } from "react-icons/cg";
import { FaSpinner } from "react-icons/fa6";
import { IoMdHeart } from "react-icons/io";
import { IoStar } from "react-icons/io5";
import FallbackImage from "../FallbackImage";

const LightBlueProductCard = ({ product }) => {
  const t = useTranslations("cart");
  const w = useTranslations("wishlist");
  const e = useTranslations();
  const { currencyShortname, rate } = useCurrency();
  const { addToCart: addToCartLocal, updateCart } = useCart();
  const [isPending, setIsPending] = useState(false);
  const [isFavLoading, setIsFavLoading] = useState(false);
  const { wishlist, toggleItem } = useWishlistStore(); // Access wishlist state
  const isWishlisted = wishlist?.some(
    (wishlistItem) => wishlistItem?.id == product?.id
  ); // Check if in wishlist
  const locale = useLocale();
  const productPhoto = product.cover_photo ?? product.product_photos[0]?.photo; // Display product photo
  const productTitle =
    product?.title || "" || product?.product_details?.[0]?.title || "";

  // Toggle wishlist item
  const handleToggleItem = async () => {
    setIsFavLoading(true);
    const token = await getToken();
    if (token) {
      try {
        const data = new FormData();
        data.append("product_id", product.id);
        const response = await postData({
          endPoint: "/product/favourites",
          body: data,
          token,
          locale,
        });
        if (response.status === "success") {
          setIsFavLoading(false);
          toastSuccess(response.message);
          toggleItem(product); // Update wishlist store
        } else {
          setIsFavLoading(false);
          toastError(response?.message || e("error-message"));
        }
      } catch (error) {
        setIsFavLoading(false);
        toastError(e("error-message"));
      }
    } else {
      setIsFavLoading(false);
      toastError(w("mustsign"));
    }
  };
  // Add to cart
  const handleAddToCart = async () => {
    setIsPending(true);
    const token = await getToken();
    if (token) {
      const { message, code } = await addToCart(product.id);
      setIsPending(false);
      if (code !== 200) {
        toastError(message || t("add-fail"));
        return;
      }
      updateCart();
      toastSuccess(message || t("add-success"));
    } else {
      setIsPending(false);
      addToCartLocal(product);
      toastSuccess(t("add-success"));
    }
  };
  return (
    <div className="bldock rounded-md bg-white flex flex-col justify-between h-full p-2 md:p-4 lg:p-8 space-y-4 hover:shadow-lg hover:bg-light transition-all duration-500">
      {/* Wishlist and rating */}
      <div className="flex items-center  justify-between">
        <div
          className={`size-7  rounded-full flex items-center justify-center ${isWishlisted ? "text-red-500 bg-white shadow" : "text-white bg-main"
            } hover:text-red-500 hover:bg-white hover:shadow transition-all duration-300`}
        >
          {isFavLoading ? (
            <FaSpinner className="animate-spin" />
          ) : (
            <IoMdHeart
              size={18}
              onClick={handleToggleItem}
              className="cursor-pointer"
            />
          )}
        </div>

        {/* Discount */}
        {product.discount && (
          <div className="bg-green-500 text-xs text-white size-7 rounded-full flex items-center justify-center ">
            {Math.floor(product.discount)}%
          </div>
        )}
      </div>

      {/* Product image and details */}
      <Link href={`/products/${product.id}`} className=" block space-y-4">
        <div className=" h-24 md:h-36 relative">
          <FallbackImage
            src={productPhoto}
            alt={product.title || "product"}
            fill
            className="object-contain"
          />
        </div>
        <div className=" space-y-2 3xl:text-xl text-lg text-center">
          <h3 className=" line-clamp-1">{productTitle}</h3>
          <div className="text-center flex items-center justify-center">
            <p className="font-bold space-x-2">
              {parseFloat(
                (product.price - product.price * (product.discount / 100)) *
                rate
              ).toFixed(2)}
              &nbsp;
              <span className="text-sm text-main">{currencyShortname}</span>
            </p>
            {product.discount && (
              <del className="font-light space-x-2 text-gray-300">
                {parseFloat(product.price * rate).toFixed(2)}
              </del>
            )}
          </div>
          {product.rate && (
            <div className="flex items-center gap-1 justify-center">
              {Array.from({ length: Math.floor(product.rate) }, (_, i) => (
                <IoStar
                  key={`yellow-${i}`}
                  size={16}
                  className="text-yellow-400"
                />
              ))}
              {Array.from({ length: 5 - Math.floor(product.rate) }, (_, i) => (
                <IoStar key={`gray-${i}`} size={16} className="text-gray-300" />
              ))}
              <p className="text-sm font-semibold pt-1">
                {parseFloat(product.rate).toFixed(1)}
              </p>
            </div>
          )}
        </div>
      </Link>

      {/* Add to cart button */}
      <button
        disabled={isPending}
        onClick={handleAddToCart}
        className="group btn btn-main rounded-full self-end h-12 max-md:h-9 max-md:text-xs flex items-center justify-center w-full  mx-auto"
      >
        {isPending ? (
          <Loader2 size={20} className="text-[#FEC958] animate-spin " />
        ) : (
          <>
            {t("add-to-cart")}
            &nbsp;
            <CgShoppingCart
              size={20}
              className="text-[#FEC958] max-md:hidden"
            />
          </>
        )}
      </button>
    </div>
  );
};

export default LightBlueProductCard;
