import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import { useReceiptStore } from "@/zustand/receiptStore";
import {
  useClearCart,
  useDecrementCart,
  useGetCartItems,
  useIncrementCart,
} from "../hooks/useCartData";

export const useCart = () => {
  const { isSuccess } = useGetProfile();
  const { clear, increment, decrement, items } = useReceiptStore();
  const { mutate: mutateIncrementCart } = useIncrementCart();
  const { mutate: mutateDecrementCart } = useDecrementCart();
  const { mutate: mutateClearCart } = useClearCart();
  const { data: cartItems } = useGetCartItems(isSuccess);

  const addToCart = (id: string | number) => {
    if (isSuccess) {
      mutateIncrementCart(id);
    } else {
      increment(id);
    }
  };

  const removeFromCart = (id: string | number) => {
    if (isSuccess) {
      mutateDecrementCart(id);
    } else {
      decrement(id);
    }
  };

  const clearCart = () => {
    if (isSuccess) {
      mutateClearCart();
    } else {
      clear();
    }
  };

  const getCartItems = () => {
    if (isSuccess) {
      if (!cartItems?.data?.items) {
        return {};
      }
      return cartItems.data.items.reduce((acc, item) => {
        acc[item.foodId] = { quantity: item.quantity };
        return acc;
      }, {} as Record<string | number, { quantity: number }>);
    } else {
      return items;
    }
  };

  const isItemLoading = () => {
    return false;
  };

  return {
    items: getCartItems(),
    increment,
    decrement,
    clear,
    addToCart,
    removeFromCart,
    clearCart,
    isItemLoading,
  };
};
