"use client";

import { useCustomToast } from "./useToast";
import { useAppDispatch } from "@/store/hooks";
import { addItem, clearCart } from "@/store/slices/cart-slice";
import { isObject } from "@utils/type-guards";
import { getCartToken } from "@utils/getCartToken";
import { getCookie, setCookie, deleteCookie } from "@utils/cookie-tools";
import { encodeJWT } from "@/utils/jwt-cookie";
import { useGuestCartToken } from "./useGuestCartToken";
import { IS_GUEST,GUEST_CART_TOKEN,GUEST_CART_ID } from "@/utils/constants";
import { useMutation } from "@apollo/client/react";
import {
  CREATE_ADD_PRODUCT_IN_CART,
  REMOVE_CART_ITEM,
  UPDATE_CART_ITEM,
} from "@/graphql";
import { formatCartDetail } from "@/utils/cartDetailTools";



export const useAddProduct = () => {
  const dispatch = useAppDispatch();
  const { createGuestToken } = useGuestCartToken();
  const { showToast } = useCustomToast();

  const [mutateAsync, { loading: isCartLoading }] = useMutation(
    CREATE_ADD_PRODUCT_IN_CART,
    {
      onCompleted: (res) => {
        console.log('useAddToCart onCompleted run ----- 0');
        const responseData = res?.createAddProductInCart?.addProductInCart;

        if (!responseData?.success) {
          showToast(responseData?.message || "Error adding to cart", "danger");
          return;
        }
        if (responseData) {
          if (responseData.success) {
            /** 兜底代码 start*/
            // 游客加购，然后清空购物车，然后刷新页面，然后再加购，然后再刷新页面，购物车会失效，所以添加兜底代码
            const isGuest = getCookie(IS_GUEST) !== "false";// 'true' 是游客
            // 如果之前的cartToken有效，responseCartId和responseCartToken的值是一样的都是cart id; 否则两者不相等
            const responseCartId = responseData.id;
            const responseCartToken = responseData.cartToken;
            if(isGuest && responseCartId !== responseCartToken) {
                const newToken = encodeJWT({
                  sessionToken: responseCartToken,
                  cartId: responseCartId,
                  isGuest: isGuest,
                });
        
                setCookie(GUEST_CART_TOKEN, newToken,{encode: false});
                setCookie(GUEST_CART_ID, responseCartId);
                setCookie(IS_GUEST, String(isGuest));
            }
            /** 兜底代码 end*/

            const cartDetail = formatCartDetail(responseData);
            dispatch(addItem(cartDetail));
            showToast("Product added to cart successfully", "success");
          }
        }
      },

      onError: (err) => {
        showToast(err?.message ?? "Error", "danger");
      },
    },
  );

  const onAddToCart = async ({
    productId,
    quantity,
    variantId
  }: {
    productId: string;
    quantity: number;
    variantId?: number;
    token?: string;
    cartId?: number | string;
  }) => {
    
    // Ensure token exists - create if needed
    let token = getCartToken(); // 从cookie获取token

    if (!token) {
      // 没有token，则创建一个并写入cookie
      token = await createGuestToken();

      if (!token) {
        showToast("Failed to create cart session", "danger");
        return;
      }
    }
    
    const param : { productId: number; quantity:number; variantId?: number; } = {
      productId: parseInt(productId),
      quantity,
    };
    if(variantId) {
      param.variantId = variantId;
    }

    const result = await mutateAsync({
      variables: param,
    });

    return {
      data: result.data,
      error: result.error,
    };
  };

  //--------Remove Cart Product Quantity--------//
  const [removeFromCart, { loading: isRemoveLoading }] = useMutation(
    REMOVE_CART_ITEM,
    {
      onCompleted: async (response) => {
        const responseData = response?.createRemoveCartItem?.removeCartItem;
        if (isObject(responseData)) {
          const message = "Cart item removed successfully";
          const cartDetail = formatCartDetail(responseData);
          dispatch(addItem(cartDetail));
          showToast(message as string, "warning");

          if (!responseData?.itemsQty) {
            dispatch(clearCart());

            const isGuest = getCookie(IS_GUEST);
            if (isGuest === "true") {
              deleteCookie(GUEST_CART_TOKEN);
              deleteCookie(GUEST_CART_ID);
            }
          }
        } else {
          showToast("Something went wrong", "warning");
        }
      },
      onError: (error) => {
        showToast(error?.message as string, "danger");
      },
    },
  );

  const onAddToRemove = async (productId: string) => {
    await removeFromCart({
      variables: {
        cartItemId: parseInt(productId),
      },
    });
  };

  //---------Update Cart Product Quantity--------//
  const [updateCartItem, { loading: isUpdateLoading }] = useMutation(
    UPDATE_CART_ITEM,
    {
      onCompleted: (response) => {
        const responseData = response?.createUpdateCartItem?.updateCartItem;

        if (isObject(responseData)) {
          const cartDetail = formatCartDetail(responseData);
          dispatch(addItem(cartDetail));
        } else {
          showToast("Something went wrong!", "warning");
        }
      },

      onError: (error) => {
        showToast(error?.message as string, "danger");
      },
    },
  );

  const onUpdateCart = async ({
    cartItemId,
    quantity,
  }: {
    cartItemId: number;
    quantity: number;
  }) => {
    if (quantity < 1) {
      showToast("Quantity must be at least 1", "warning");
      return;
    }

    await updateCartItem({
      variables: {
        cartItemId: cartItemId,
        quantity,
      },
    });
  };

  return {
    isCartLoading,
    onAddToCart,
    isRemoveLoading,
    onAddToRemove,
    onUpdateCart,
    isUpdateLoading,
  };
};
