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

const CartContext = createContext({
    items:[], addToCart(){}, removeFromCart(){},countItems(){return 0}, removeProduct(){}, clearCart(){}
})

export const useCart = ()=> useContext(CartContext)


export const CartProvider=({children})=> {
    const [cartItems, setCartItems] = useState([])
    const updateCartInLs = (cartItems)=>{
      localStorage.setItem('CartItems',JSON.stringify(cartItems))
    }
  
    const addToCart =(product, qty)=> {
        const oldCartItems = [...cartItems]
          const index = cartItems.findIndex(item =>product.id ===item.product.id)
           if (index ===-1){
            oldCartItems.push({count:qty, product})
           }
           else{
            oldCartItems[index].count +=qty
           }
           setCartItems(oldCartItems)
           updateCartInLs(oldCartItems)
    }

    const removeProduct =(product)=> {
          const newProducts = cartItems.filter(item =>product.id !==item.product.id)
           
           setCartItems(newProducts)
           updateCartInLs(newProducts)
    }

    const removeFromCart =(product, qty)=> {
        const finalProduct = cartItems.map(item =>{
          if(product.id ===item.product.id){
              item.count -= qty
          }
            return item
      })
      setCartItems(finalProduct)
      updateCartInLs(finalProduct)

  }

  const countItems = ()=>{
   return cartItems.reduce((total,cartItem)=> total + cartItem.count, 0)
  }
const clearCart = ()=>{
  setCartItems([])
  updateCartInLs([])
}

useEffect(
  ()=>{
    const result = localStorage.getItem('CartItems');
    if(result != null){
      setCartItems(JSON.parse(result))
    }
  },[]
);
  
  return (
    <CartContext.Provider value={{items:cartItems, addToCart, removeFromCart, countItems, removeProduct, clearCart 

    }}>
{children}
    </CartContext.Provider>
  )
}

