"use client"

import React, { createContext, useContext, useState, useCallback, useEffect } from 'react'
import { CartItem, saveCart, getCart, clearCart } from '@/lib/cartStorage'

type CartContextType = {
  items: CartItem[]
  addToCart: (item: Omit<CartItem, 'quantity'>) => void
  removeFromCart: (id: number) => void
  removeAllFromCart: (id: number) => void
  updateQuantity: (id: number, quantity: number) => void
  clearCart: () => void
  getTotalItems: () => number
}

const CartContext = createContext<CartContextType | undefined>(undefined)

export const useCart = () => {
  const context = useContext(CartContext)
  if (!context) {
    throw new Error('useCart must be used within a CartProvider')
  }
  return context
}

export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [items, setItems] = useState<CartItem[]>([])

  useEffect(() => {
    const savedCart = getCart()
    if (savedCart.length > 0) {
      setItems(savedCart)
    }
  }, [])

  useEffect(() => {
    saveCart(items)
  }, [items])

  const addToCart = useCallback((newItem: Omit<CartItem, 'quantity'>) => {
    setItems(currentItems => {
      const existingItem = currentItems.find(item => item.id === newItem.id)
      if (existingItem) {
        return currentItems.map(item =>
          item.id === newItem.id ? { ...item, quantity: item.quantity + 1 } : item
        )
      }
      return [...currentItems, { ...newItem, quantity: 1 }]
    })
  }, [])

  const removeFromCart = useCallback((id: number) => {
    setItems(currentItems => {
      const existingItem = currentItems.find(item => item.id === id)
      if (existingItem && existingItem.quantity > 1) {
        return currentItems.map(item =>
          item.id === id ? { ...item, quantity: item.quantity - 1 } : item
        )
      }
      return currentItems.filter(item => item.id !== id)
    })
  }, [])

  const removeAllFromCart = useCallback((id: number) => {
    setItems(currentItems => currentItems.filter(item => item.id !== id))
  }, [])

  const updateQuantity = useCallback((id: number, quantity: number) => {
    setItems(currentItems => 
      currentItems.map(item => 
        item.id === id ? { ...item, quantity: Math.max(1, quantity) } : item
      )
    )
  }, [])

  const clearCartItems = useCallback(() => {
    setItems([])
    clearCart()
  }, [])

  const getTotalItems = useCallback(() => {
    return items.reduce((total, item) => total + item.quantity, 0)
  }, [items])

  return (
    <CartContext.Provider value={{ 
      items, 
      addToCart, 
      removeFromCart, 
      removeAllFromCart, 
      updateQuantity, 
      clearCart: clearCartItems, 
      getTotalItems 
    }}>
      {children}
    </CartContext.Provider>
  )
}

