"use client";
import { getToken } from "@/actions/cookies";
import addToCart from "@/api/cart/addToCart";
import postData from "@/api/post-data";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toastError, toastSuccess } from "@/services/custom-toast";
import useCart from "@/stores/cart";
import { useCurrency } from "@/stores/currency-state";
import useWishlistStore from "@/stores/wishlist"; // Import the Zustand store
import { useTranslations } from "next-intl";
import { useState } from "react";
import { FaSpinner } from "react-icons/fa";
import { IoCloseSharp } from "react-icons/io5";
import AlertWarning from "../AlertWarning";
import FallbackImage from "../FallbackImage";

export default function WishlistUi({ data }) {
  const t = useTranslations("wishlist");
  const c = useTranslations("cart");
  const [deletingItemId, setDeletingItemId] = useState(null);
  const [wishlist, setWishlist] = useState(data?.data);
  const [isAddingProduct, setIsAddingProduct] = useState(false);
  const { toggleItem } = useWishlistStore(); // Destructure toggleItem from Zustand store
  const { currencyShortname, rate } = useCurrency();
  const { updateCart, addToCart: addToCartLocal } = useCart();
  const [cartLoading, setCartLoading] = useState(false);
  // Handle remove item from wishlist
  // Handle remove item from wishlist
  const handleRemoveItem = async (itemId) => {
    setDeletingItemId(itemId);

    // Send delete request
    const formData = new FormData();
    formData.append("product_id", itemId);
    const response = await postData({
      endPoint: "/product/favourites",
      body: formData,
    });

    if (response.status === "success") {
      // Update Zustand store first
      toggleItem({ id: itemId });

      // Update the local state
      setWishlist((prev) => prev.filter((item) => item.id !== itemId));

      // Display success message
      toastSuccess(response.message);
    }

    setDeletingItemId(null);
  };
  async function handleAddToCart(product) {
    setIsAddingProduct(true);
    const token = await getToken();
    if (token) {
      const { message, code } = await addToCart(product.id);
      if (code !== 200) {
        setIsAddingProduct(false);
        toastError(message);
        return;
      }
      setIsAddingProduct(false);
      toastSuccess(message);
      updateCart();
    } else {
      setIsAddingProduct(false);
      addToCartLocal(product);
      toastSuccess(c("add-success"));
    }
  }

  if (!wishlist || wishlist.length === 0) {
    return <AlertWarning text={t("noProducts")} />;
  }

  return (
    <section>
      <div className="container lg:my-10">
        <Table>
          <TableHeader className=" lg:py-10  bg-main text-white" >
            <TableRow className="lg:font-extrabold mx-2 px-2  ">
              <TableHead className="lg:text-xl text-start xl:ps-10 ">
                {t("product")}
              </TableHead>
              <TableHead className="lg:text-xl text-start ">
                {t("price")}
              </TableHead>
              <TableHead className="lg:text-xl text-start ">
                {t("details")}
              </TableHead>
              <TableHead className="lg:text-xl text-start ">
                {t("delete")}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {wishlist?.map((item) => (
              <TableRow key={item.id} className="lg:text-xl shadow">
                <TableCell className="lg:flex text-start items-center lg:gap-3">
                  <FallbackImage
                    src={item.photo}
                    placeholderSrc={"/products/Placeholder.png"}
                    alt={item.title}
                    width={100}
                    height={100}
                    className="object-contain h-20 md:h-32"
                  />
                  <div>
                    <h4 className="max-lg:text-start">{item.title}</h4>
                  </div>
                </TableCell>
                <TableCell className="text-start">
                  <span className="lg:font-extrabold mx-2">
                    {parseFloat(
                      (item.price - item.price * (item.discount / 100)) * rate
                    ).toFixed(2)}
                  </span>
                  <span className="text-xs font-semibold">
                    {currencyShortname}
                  </span>
                </TableCell>
                <TableCell className="text-start">
                  <Button
                    variant="outline"
                    onClick={() => handleAddToCart(item)}
                    className="hover:bg-transparent hover:text-main font-extrabold w-24 xl:w-36  hover:border-main text-white bg-main"
                  >
                    {!isAddingProduct ? t("add-product") : <FaSpinner className="animate-spin " />}
                  </Button>
                </TableCell>
                <TableCell className="text-start">
                  <button
                    onClick={() => handleRemoveItem(item.id)}
                    className={`hover:text-red-500 text-3xl ${deletingItemId && deletingItemId !== item.id
                      ? "opacity-50 cursor-not-allowed"
                      : ""
                      }`}
                    disabled={!!deletingItemId}
                  >
                    {deletingItemId === item.id ? (
                      <FaSpinner className="animate-spin" />
                    ) : (

                      <IoCloseSharp />
                    )}
                  </button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </section>
  );
}
