"use client"
import { SessionProvider } from 'next-auth/react'
import React, { createContext, useEffect, useState } from 'react'
import toast from 'react-hot-toast';


export const CartContext = createContext({});
export function productTotal(cartProduct){
  let price = cartProduct.basePrice;
  if(cartProduct.size){
    price += cartProduct.size.price;
  }
  if(cartProduct.extra?.length > 0){
    for(const extras of cartProduct.extra){
      price += extras.price
    }
  }
  return price
}

const AppProvider = ({children}) => {
  const [cartProducts, setCartProducts] = useState([]);

  const ls = typeof window !== 'undefined' ? window.localStorage : null;


  useEffect(() => {
    if(ls && ls.getItem('cart')){
      setCartProducts( JSON.parse( ls.getItem('cart') ) )
    }
  }, []);

  function clearCart(){
    setCartProducts([]);
    saveCartProductsToLocalStorage([]);
  }

  function removeCartProduct(indexToRemove){
    setCartProducts(prevCartProducts => {
      const newCartProducts = prevCartProducts.filter((v, index) => index !== indexToRemove);
      saveCartProductsToLocalStorage(newCartProducts);
      return newCartProducts;
    });
    toast.success('Item is removed')
  }

  function saveCartProductsToLocalStorage(cartProducts){
    if(ls){
      ls.setItem('cart', JSON.stringify(cartProducts))
    }
  }

  function addToCart(product, size=null, extra=[]){
    setCartProducts(prevProducts => {
      const cartProduct = {...product, size, extra}
      const newProducts = [...prevProducts, cartProduct];
      saveCartProductsToLocalStorage(newProducts);
      return newProducts
    })
  }

  return (
    <SessionProvider>
      <CartContext.Provider value={{cartProducts, setCartProducts, addToCart, clearCart, removeCartProduct}}>
        {children}
      </CartContext.Provider>
    </SessionProvider>
  )
}

export default AppProvider