"use client";
import postData from "@/api/post-data";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toastSuccess } from "@/services/custom-toast";
import useWishlistStore from "@/stores/wishlist"; // Import the Zustand store
import { useTranslations } from "next-intl";
import Link from "next/link";
import { useState } from "react";
import { FaSpinner } from "react-icons/fa";
import { HiOutlineTrash } from "react-icons/hi2";
import AlertWarning from "../shared/AlertWarning";
import FallbackImage from "../shared/FallbackImage";
import CurrencySwitcher from "../shared/CurrencySwitcher";
import { useCurrency } from "@/stores/currency-state";

export default function WishlistUi({ 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 { currencyShortname } = useCurrency();
  // 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);
  };

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

  return (
    <section>
      <div className="container lg:my-10">
        <Table>
          <TableHeader className="bg-light lg:py-10 text-white">
            <TableRow className="lg:font-extrabold">
              <TableHead className="lg:text-xl text-center text-black">
                {t("product")}
              </TableHead>
              <TableHead className="lg:text-xl text-center text-black">
                {t("price")}
              </TableHead>
              <TableHead className="lg:text-xl text-center text-black">
                {t("delete")}
              </TableHead>
              <TableHead className="lg:text-xl text-center text-black">
                {t("details")}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {wishlist?.map((item) => (
              <TableRow key={item.id} className="lg:text-xl shadow">
                <TableCell className="lg:flex text-center 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-center">
                  <span className="lg:font-extrabold mx-2">
                    {parseFloat(
                      item.price - item.price * (item.discount / 100)
                    ).toFixed(2)}
                  </span>
                  <span className="text-xs font-semibold">
                    {currencyShortname}
                  </span>
                </TableCell>
                <TableCell className="text-center">
                  <button
                    onClick={() => handleRemoveItem(item.id)}
                    className={`hover:text-red-500 ${deletingItemId && deletingItemId !== item.id
                      ? "opacity-50 cursor-not-allowed"
                      : ""
                      }`}
                    disabled={!!deletingItemId}
                  >
                    {deletingItemId === item.id ? (
                      <FaSpinner className="animate-spin" />
                    ) : (
                      <HiOutlineTrash className="size-8" />
                    )}
                  </button>
                </TableCell>
                <TableCell className="text-center">
                  <Link
                    href={`/products/${item.id}`}
                    className="underline line-clamp-1 hover:text-main text-[#353535]"
                  >
                    {t("product-details")}
                  </Link>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </section>
  );
}
