import { useState, useEffect } from "react";
import { getCartIdentifier } from "@/utils";
import { getCart, addToCart, updateCartItem, removeFromCart } 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);

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

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

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

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

  const removeItem = async (skuId: string) => {
    try {
      setLoading(true);
      const identifier = getCartIdentifier();
      await removeFromCart(identifier, skuId);
      await fetchCart();
    } finally {
      setLoading(false);
    }
  };

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