"use client";
import { useEffect, useState } from "react";
import axiosInstanceClient from "@/utils/axiosClient";
import { getAllCartItems } from "@/store/cart.slice";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "@/store/store";
import debounce from "debounce";
import CartCard from "@/shared/card/CartCard";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import CartSummary from "./CartSummary";
import EmptyCart from "./EmptyCart";
import LoaderWrapper from "@/shared/Loader/LoaderWrapper";
import { useTranslations } from "next-intl";

export default function CartCopmonent() {
  const t = useTranslations();
  const dispatch = useDispatch<AppDispatch>();
  const {
    subTotal,
    totalPrice,
    items: cartitems,
    mainLoader,
    shipping_price,
    tax_amount,
  } = useSelector((state: RootState) => state.CartConfig);

  const [loadingStates, setLoadingStates] = useState<{
    [key: string]: boolean;
  }>({});

  const [isLoadingFirstTime, setIsLoadingFirstTime] = useState(true);

  useEffect(() => {
    const fetchCartItems = async () => {
      try {
        if (Object.values(loadingStates).every((state) => !state)) {
          await dispatch(getAllCartItems());
        }
      } catch (error) {
        console.error("Error fetching cart items:", error);
      } finally {
        setIsLoadingFirstTime(false);
      }
    };

    fetchCartItems();
  }, [loadingStates]);

  const incrementQuantity = async (item: any) => {
    setLoadingStates((prev) => ({ ...prev, [item?.product?.id]: true }));
    try {
      const formData = new FormData();
      formData.append("amount", "1");
      formData.append("product_id", item?.product?.id);
      await axiosInstanceClient.post("client/carts/increment", formData);
    } catch (error: any) {
      ShowAlertMixin({
        icon: "error",
        title: error?.response?.data?.message,
      });
    } finally {
      setLoadingStates((prev) => ({ ...prev, [item?.product?.id]: false })); // Reset loading for the specific item
    }
  };
  const debouncedAddToCart = debounce(async (item) => {
    await incrementQuantity(item);
  }, 300);
  const handleAddToCart = (item: any, amount: number) => {
    const updatedItem = {
      product: item.product,
      amount: amount,
    };
    debouncedAddToCart(updatedItem);
  };

  //Decrement
  const decrementQuantity = async (item: any) => {
    setLoadingStates((prev) => ({ ...prev, [item?.product?.id]: true }));
    try {
      const formData = new FormData();
      formData.append("amount", "1");
      formData.append("product_id", item?.product?.id);

      await axiosInstanceClient.post("client/carts/decrement", formData);
    } catch (error: any) {
      ShowAlertMixin({
        icon: "error",
        title: error?.response?.data?.message,
      });
    } finally {
      setLoadingStates((prev) => ({ ...prev, [item?.product?.id]: false }));
    }
  };
  const debouncedDecreaseQuantity = debounce(async (item) => {
    await decrementQuantity(item);
  }, 300);

  const handleDecreaseQuantity = (item: any, amount: number) => {
    if (amount > 1) {
      const updatedItem = {
        product: item.product,
        amount: amount,
      };
      debouncedDecreaseQuantity(updatedItem);
    } else {
      removeFromCart(item?.product?.id);
    }
  };

  //Remove
  const removeFromCart = async (productID: any) => {
    setLoadingStates((prev) => ({ ...prev, [productID]: true }));
    try {
      const formData = new FormData();
      formData.append("product_id", productID);
      await axiosInstanceClient.post(`client/carts/remove`, formData);
    } catch (error: any) {
      ShowAlertMixin({
        icon: "error",
        title: error?.response?.data?.message,
      });
    } finally {
      setLoadingStates((prev) => ({ ...prev, [productID]: false }));
    }
  };
  const handleRemoveFromCart = (item: any) => {
    removeFromCart(item?.product?.id);
  };

  if (isLoadingFirstTime) return <LoaderWrapper />;
  if (cartitems?.length == 0) return <EmptyCart />;

  return (
    <>
      <section className="relative bg-gradient-to-br from-primary-light to-white overflow-hidden">
        <div className="container py-8 md:py-12">
          <div className="text-center max-w-3xl mx-auto">
            <div className="inline-flex items-center gap-2 bg-white px-4 py-2 rounded-full mb-4 shadow-sm">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="lucide lucide-sparkles text-primary"
              >
                <path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"></path>
                <path d="M20 3v4"></path>
                <path d="M22 5h-4"></path>
                <path d="M4 17v2"></path>
                <path d="M5 18H3"></path>
              </svg>
              <span className="text-sm">{t("Text.ready_for_payment")}</span>
            </div>
            <h1 className="text-3xl md:text-4xl mb-4 text-text-primary">
              {t("Text.shopping_cart")}
            </h1>
            <p className="text-base md:text-lg text-text-secondary leading-relaxed">
              {t("Text.you_have")} {cartitems?.length} {t("Text.products_in_cart")} - {t("Text.complete_your_order")}
            </p>
          </div>
        </div>
      </section>
      <div className="container">
        <h1 className="text-3xl md:text-4xl my-5">{t("Text.shopping_cart")}</h1>
        <div className="grid lg:grid-cols-[2fr_1fr] gap-4 my-5">
          {/* CartDetails */}
          <div key="CartDetails" className="h-fit grid gap-4 mb-4">
            {cartitems?.map((ele: any, index: number) => (
              <CartCard
                handleDecreaseQuantity={handleDecreaseQuantity}
                handleAddToCart={handleAddToCart}
                handleRemoveFromCart={handleRemoveFromCart}
                cartData={ele}
                index={`${ele.product.id}-${ele.product.title}`}
                key={`${ele.product.id}-${ele.product.title}`}
                loading={loadingStates[ele.product.id] || false} // Pass loading state for the specific item
              />
            ))}
          </div>

          {/* CartSummary */}
          <CartSummary
            subTotal={subTotal}
            totalPrice={totalPrice}
            shipping_price={shipping_price}
            tax_amount={tax_amount}
            mainLoader={mainLoader}
          />
        </div>
      </div>
    </>
  );
}
