"use client";
import { getToken } from "@/actions/cookies";
import decrementQuantityFromAPI from "@/api/cart/decrementQuantity";
import deleteFromCart from "@/api/cart/deleteFromCart";
import incrementQuantityFromAPI from "@/api/cart/incrementQuantity";
import { toastSuccess } from "@/services/custom-toast";
import useCart from "@/stores/cart";
import { useCurrency } from "@/stores/currency-state";
import { useQueryClient } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { FaMinus, FaPlus } from "react-icons/fa";
import { FaSpinner } from "react-icons/fa6";
import { IoCloseSharp } from "react-icons/io5";
import FallbackImage from "../shared/FallbackImage";

const CartCard = ({ product }) => {
  const locale = useLocale();
  const t = useTranslations("cart");
  const { removeFromCart, incrementQuantity, decrementQuantity } = useCart();
  const { currencyShortname, rate } = useCurrency();
  const [removePending, setRemovePending] = useState(false);
  const [incrementPending, setIncrementPending] = useState(false);
  const [decrementPending, setDecrementPending] = useState(false);
  const queryClient = useQueryClient();

  const hasAuction = product?.has_acution;

  async function handleRemoveFromCart() {
    setRemovePending(true);
    const token = await getToken();
    if (token) {
      // If the user is logged in
      const { message, status } = await deleteFromCart(product.id);
      setRemovePending(false);
      if (status !== "success") {
        toastError(message);
        return;
      }
      toastSuccess(message);
      queryClient.refetchQueries({
        queryKey: ["/cart/items", locale],
      });
    } else {
      // If the user is not logged in
      setRemovePending(false);
      removeFromCart(product.id);
      toastSuccess(t("delete-success"));
    }
  }

  async function handleIncrement() {
    setIncrementPending(true);
    const token = await getToken();
    if (token) {
      // If the user is logged in
      const { message, status } = await incrementQuantityFromAPI(
        product.id,
        product.quantity
      );
      setIncrementPending(false);
      if (status !== "success") {
        toastError(message);
        return;
      }
      toastSuccess(message);
      queryClient.refetchQueries({
        queryKey: ["/cart/items", locale],
      });
    } else {
      // If the user is not logged in, update locally
      setIncrementPending(false);
      incrementQuantity(product.id);
      toastSuccess(t("increment-success"));
    }
  }

  async function handleDecrement() {
    setDecrementPending(true);
    const token = await getToken();
    if (token) {
      // If the user is logged in
      const { message, status } = await decrementQuantityFromAPI(
        product.id,
        product.quantity
      );
      setDecrementPending(false);
      if (status !== "success") {
        toastError(message);
        return;
      }
      queryClient.refetchQueries({
        queryKey: ["/cart/items", locale],
      });
      toastSuccess(message);
    } else {
      // If the user is not logged in, update locally
      setDecrementPending(false);
      decrementQuantity(product.id);
      toastSuccess(t("decrement-success"));
    }
  }

  return (
    <div className="grid grid-cols-12 gap-2 w-full">
      {/* image */}
      <div className="col-span-3 border rounded-md shadow h-24 relative">
        <FallbackImage
          src={product.cover_photo}
          alt={`${product.title}'s image`}
          fill
          className="object-contain"
        />
      </div>
      {/* content */}
      <div className="col-span-8">
        <div className="space-y-4">
          {/* title */}
          <p className="text-lg font-semibold min-h-8 line-clamp-1">
            {product.title}
          </p>
          {/* price and quantity */}
          <div className="flex gap-8 items-center">
            {/* price */}
            <p className="text-main font-semibold">
              {(() => {
                // Handle undefined or null product
                if (
                  !product ||
                  product.price === undefined ||
                  product.price === null
                ) {
                  return "0.00";
                }

                // Handle string prices with commas
                let price = product.price;
                if (typeof price === "string") {
                  price = price.replace(/,/g, ""); // Remove commas
                }

                // Parse to number and ensure rate is valid
                const numPrice = parseFloat(price);
                const numRate = parseFloat(rate) || 1; // Use 1 as default rate if invalid

                // Check for valid calculation result
                if (isNaN(numPrice)) {
                  return "0.00";
                }

                return (numPrice * numRate).toFixed(2);
              })()}{" "}
              <span className="text-sm text-secondary">
                {currencyShortname}
              </span>
            </p>
            {/* Quantity */}
            <div className="flex items-center gap-4">
              {!hasAuction && (
                <button
                  disabled={product.quantity <= 1 || decrementPending}
                  onClick={handleDecrement}
                  className="size-5 border-2  border-black  rounded-full flex items-center justify-center text-black"
                >
                  {decrementPending ? (
                    <FaSpinner className="animate-spin" />
                  ) : (
                    <FaMinus size={12} />
                  )}
                </button>
              )}
              <p className="text-xl font-semibold">{product.quantity}</p>
              {!hasAuction && (
                <button
                  disabled={incrementPending}
                  onClick={handleIncrement}
                  className="size-5 border-2  border-black  rounded-full flex items-center justify-center text-black"
                >
                  {incrementPending ? (
                    <FaSpinner className="animate-spin" />
                  ) : (
                    <FaPlus size={12} />
                  )}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
      {/* remove */}
      <div className="col-span-1 h-full content-center">
        <button
          disabled={removePending}
          onClick={handleRemoveFromCart}
          className="text-gray-400"
        >
          {removePending ? (
            <FaSpinner className="animate-spin" />
          ) : (
            <IoCloseSharp size={20} />
          )}
        </button>
      </div>
    </div>
  );
};

export default CartCard;
