import React, { createContext, useState, useEffect } from 'react'

export const CartContext = createContext()

export const CartProvider = ({ children }) => {
  const [cart, setCart] = useState([])
  const [total, setTotal] = useState(0)

  useEffect(() => {
    calculateTotal()
  }, [cart])

  const calculateTotal = () => {
    const newTotal = cart.reduce((sum, item) => {
      const price = item.product.discount_price || item.product.price
      return sum + price * item.quantity
    }, 0)
    setTotal(newTotal)
  }

  const addToCart = (product, quantity = 1, size = null) => {
    const existingItem = cart.find(
      (item) =>
        item.product.id === product.id &&
        item.size === size
    )

    if (existingItem) {
      setCart(
        cart.map((item) =>
          item === existingItem
            ? { ...item, quantity: item.quantity + quantity }
            : item
        )
      )
    } else {
      setCart([...cart, { product, quantity, size }])
    }
  }

  const removeFromCart = (index) => {
    setCart(cart.filter((_, i) => i !== index))
  }

  const updateQuantity = (index, quantity) => {
    if (quantity <= 0) {
      removeFromCart(index)
    } else {
      setCart(
        cart.map((item, i) =>
          i === index ? { ...item, quantity } : item
        )
      )
    }
  }

  const clearCart = () => {
    setCart([])
  }

  return (
    <CartContext.Provider
      value={{
        cart,
        total,
        addToCart,
        removeFromCart,
        updateQuantity,
        clearCart,
      }}
    >
      {children}
    </CartContext.Provider>
  )
}
