"use client";
import addToCart from "@/api/cart/addToCart";
import postData from "@/api/post-data";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useCurrency } from "@/stores/currency-state";
import useWishlistStore from "@/stores/wishlist"; // Import the Zustand store
import { useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
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";
import { getToken } from "@/actions/cookies";
import useCart from "@/stores/cart";

export default function WishlistRedesignThree({ data }) {
  const t = useTranslations("wishlist");
  const [deletingItemId, setDeletingItemId] = useState(null);
  const [wishlist, setWishlist] = useState(data?.data);
  const { toggleItem } = useWishlistStore(); // Destructure toggleItem from Zustand store
  const [addToCartPending, setAddToCartPending] = useState(null);
  const queryClient = useQueryClient();
  const { currency } = useCurrency();
  const { addToCart: addToCartLocal } = useCart();

  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) {
    setAddToCartPending(product?.id);
    const token = await getToken();
    if (token) {
      const { message, code } = await addToCart(product.id);
      if (code !== 200) {
        toastError(message);
        return;
      }
      queryClient.refetchQueries({ queryKey: ["/cart/items"] });
      toastSuccess(message);
    } else {
      addToCartLocal(product);
      toastSuccess(c("add-success"));
    }
    setAddToCartPending(null);
  }
  if (!wishlist || wishlist.length === 0) {
    return <AlertWarning text={t("noProducts")} />;
  }

  return (
    <section className="container my-10 grid grid-cols-1 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 lg:gap-5">
      {wishlist?.map((item, i) => (
        <Card
          key={i}
          className="relative space-y-4 flex flex-col justify-between"
        >
          <CardHeader className="relative h-48 w-full">
            <FallbackImage
              className="object-cover object-top"
              fill
              src={item?.photo}
            />
            {/* Remove Item button */}
            <button
              onClick={() => handleRemoveItem(item.id)}
              className={`hover:text-main text-gray-500 absolute text-2xl top-2 right-4 ${
                deletingItemId && deletingItemId !== item.id
                  ? "opacity-50 cursor-not-allowed"
                  : ""
              }`}
              disabled={!!deletingItemId}
            >
              {deletingItemId === item.id ? (
                <FaSpinner className="animate-spin" />
              ) : (
                <IoCloseSharp />
              )}
            </button>
          </CardHeader>
          <CardContent className="space-y-4">
            <h1 className="text-2xl font-medium">{item?.title}</h1>
            <p className="font-medium">
              {currency} {Number(item?.price).toFixed(2)}
            </p>
            <Button
              className="w-full bg-gray-200 rounded-lg hover:bg-secondary text-main text-sm lg:text-base 2xl:text-lg font-bold"
              onClick={() => handleAddToCart(item)}
            >
              {addToCartPending === item.id ? (
                <Loader2 size={20} className="animate-spin" />
              ) : (
                t("add-to-cart")
              )}
            </Button>
          </CardContent>
        </Card>
      ))}
    </section>
  );
}
