import { useState, useEffect } from "react";
import { getCartIdentifier } from "@/utils";
import { getCart, addToCart, updateCartItem, removeFromCart,clearFromCart } from "@/services/cartApi";
import { useDispatch, useSelector } from "react-redux";
import { setCart } from "@/lib/cartSlice";

export function useCart() {
  const dispatch  = useDispatch();
  const cart = useSelector((state: any) => state.cart.items);
  const [loading, setLoading] = useState(false);
  const [modifyLoading, setModfifyLoading] = useState(false)

  // Auto-fetch on first use if cart is empty
  useEffect(() => {
    if (!cart || cart.length === 0) {
      fetchCart();
    }
  }, []);

  const fetchCart = async () => {
    try {
      setLoading(true)
      const identifier    = getCartIdentifier();
      const { data }      = await getCart(identifier);
      dispatch(setCart(data?.data?.items ?? []));
    } catch (e) {
      dispatch(setCart([]));
    } finally {
      setLoading(false)
    }
  };

  const addItem = async (productId: string, skuId: string | null = null, quantity = 1) => {
    try {
      setModfifyLoading(true);
      const identifier = getCartIdentifier();
      const response   = await addToCart(identifier, { productId, skuId, quantity });
      if (response.data?.success) await fetchCart();
      return response
    } finally {
      setModfifyLoading(false);
    }
  };

  const updateItem = async (skuId: string, quantity: number) => {
    try {
      setModfifyLoading(true);
      const identifier = getCartIdentifier();
      await updateCartItem(identifier, skuId, quantity);
      await fetchCart();
    } finally {
      setModfifyLoading(false);
    }
  };

  const removeItem = async (skuId: string) => {
    try {
      setModfifyLoading(true);
      const identifier = getCartIdentifier();
      await removeFromCart(identifier, skuId);
      await fetchCart();
    } finally {
      setModfifyLoading(false);
    }
  };
  const clearCart = async () => {
    try {
      setModfifyLoading(true);
       const guestId =localStorage.getItem("guestId") || undefined;
      const identifier = getCartIdentifier();
      await clearFromCart(identifier,guestId); // Assuming null removes all items
      await fetchCart();
    } finally {
      setModfifyLoading(false);
    }
  }

  return { cart, loading, modifyLoading, fetchCart, addItem, updateItem, removeItem,clearCart };
}