"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 { useLocale, useTranslations } from "next-intl";

import { useState } from "react";

import { useQueryClient } from "@tanstack/react-query";
import ProductCardRedesignThree from "./AdditionalProductCards/ProductCardRedesign3";

const ProductCard = ({ product, h, line }) => {
  const locale = useLocale();
  const t = useTranslations("cart");
  const w = useTranslations("wishlist");
  const e = useTranslations();
  const queryClient = useQueryClient();
  const { currency, rate } = useCurrency();
  const { addToCart: addToCartLocal } = 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 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 () => {
    const token = await getToken();
    if (token) {
      setIsFavLoading(true);
      try {
        const data = new FormData();
        data.append("product_id", product.id);
        const response = await postData({
          endPoint: "/product/favourites",
          body: data,
        });

        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 {
      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);
        return;
      }
      toastSuccess(message);
    } else {
      setIsPending(false);
      addToCartLocal(product);
      toastSuccess(t("add-success"));
    }

    queryClient.refetchQueries({
      queryKey: ["/cart/items", locale],
    });
  };

  return (
    <ProductCardRedesignThree
      product={product}
      handleToggleItem={handleToggleItem}
      handleAddToCart={handleAddToCart}
      productTitle={productTitle}
      productPhoto={productPhoto}
      isWishlist={isWishlisted}
      isFavLoading={isFavLoading}
      isPending={isPending}
      currency={currency}
      rate={rate}
      h={h}
      line={line}
    />
  );
};

export default ProductCard;
