import { create } from "zustand";
import { persist } from "zustand/middleware";

const useCart = create(
  persist(
    (set) => ({
      isCartUpdated: false,
      cart: [], // Initial cart is an empty array

      // Add an item to the cart or increment its quantity if it already exists
      addToCart: (item) =>
        set((state) => {
          const existingItem = state.cart.find(
            (cartItem) => cartItem.id === item.id
          );
          if (existingItem) {
            // If item exists, increment the quantity
            return {
              cart: state.cart.map((cartItem) =>
                cartItem.id === item.id
                  ? { ...cartItem, quantity: cartItem.quantity + 1 }
                  : cartItem
              ),
            };
          } else {
            // If item doesn't exist, add it with a quantity of 1 (if not already defined)
            return {
              cart: [...state.cart, { ...item, quantity: item.quantity || 1 }],
            };
          }
        }),
      updateCart: () =>
        set((state) => ({ isCartUpdated: !state.isCartUpdated })),
      setCart: (newCart) =>
        set(() => ({
          cart: newCart,
        })),
      // Remove an item from the cart by its ID
      removeFromCart: (id) =>
        set((state) => ({
          cart: state.cart.filter((item) => item.id !== id), // Filter out the item with the matching ID
        })),

      // Increment the quantity of an item in the cart by its ID
      incrementQuantity: (id, quantity) =>
        set((state) => ({
          cart: state.cart.map(
            (item) =>
              item.id === id
                ? { ...item, quantity: quantity || item.quantity + 1 }
                : item // Increment quantity if the ID matches
          ),
        })),

      // Decrement the quantity of an item in the cart by its ID
      decrementQuantity: (id) =>
        set((state) => ({
          cart: state.cart.map(
            (item) =>
              item.id === id
                ? { ...item, quantity: Math.max(item.quantity - 1, 1) }
                : item // Decrement quantity if the ID matches, ensuring it doesn't go below 1
          ),
        })),

      // Clear all items from the cart
      clearCart: () => set({ cart: [] }),

      // Calculate the total price of the items in the cart
      total: (state) =>
        state.cart?.reduce((acc, item) => acc + item.price * item.quantity, 0), // Sum up the price * quantity for each item
    }),
    {
      name: "cart-storage", // The name of the key in localStorage
      getStorage: () => localStorage, // Use localStorage to persist data
    }
  )
);

export default useCart;
