import {createContext, FunctionComponent, PropsWithChildren, useState} from 'react'

interface SelectedDrinkContext {
  selectedDrinkIds: Set<number>
  toggleDrinkId: (id: number) => void
  resetSelectedDrinkIds: () => void
}

export const SelectedDrinkContext = createContext<SelectedDrinkContext>({
  selectedDrinkIds: new Set(),
  toggleDrinkId: () => {
    console.warn('No implementation found for toggleDrinkId, please provide one.')
  },
  resetSelectedDrinkIds: () => {
    console.warn('No implementation found for resetSelectedDrinkIds, please provide one.')
  },
})

const SelectedDrinkProvider: FunctionComponent<PropsWithChildren> = ({children}) => {
  const [selectedDrinkIds, setSelectedDrinkIds] = useState<Set<number>>(new Set())

  const toggleDrinkId = (id: number) => {
    setSelectedDrinkIds(old => {
      const newSet = new Set(old)
      if (newSet.has(id)) {
        newSet.delete(id)
      } else {
        newSet.add(id)
      }
      return newSet
    })
  }

  return (
    <SelectedDrinkContext
      value={{selectedDrinkIds, toggleDrinkId, resetSelectedDrinkIds: () => setSelectedDrinkIds(new Set())}}>
      {children}
    </SelectedDrinkContext>
  )
}

export default SelectedDrinkProvider
