"use client"

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

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

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

export const useCart = () => {
  const context = useContext(CartContext)
  if (context === undefined) {
    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 (Array.isArray(savedCart) && savedCart.length > 0) {
      setItems(savedCart)
    }
  }, [])

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

  const addToCart = useCallback((newItem: Omit<CartItem, "quantity">, quantity = 1) => {
    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 + quantity } : item,
        )
      }
      return [...currentItems, { ...newItem, quantity }]
    })
  }, [])

  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.length
  }, [items])

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

  const getTotalUniqueItems = useCallback(() => {
    return items.length
  }, [items])

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

