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

// 1. Define data that the context holds, plus a setter to update data
interface MyContextProps {
  standalone: boolean
  setMyContext: (value: Partial<Omit<MyContextProps, 'setMyContext'>>) => void
}

// 2. Create the actual context with some default data
const MyAppContext = React.createContext<MyContextProps>({
  standalone: true,
  setMyContext: () => {}
})

// 3. Define the context provider
export const MyContextProvider: React.FC<{ value: MyContextProps }> = ({ value: initialValue, children }) => {
  const [states, setStates] = useState<MyContextProps>(initialValue)

  return (
    <MyAppContext.Provider
      value={{
        ...states,
        setMyContext: props => {
          setStates({ ...states, ...props })
        }
      }}>
      {children}
    </MyAppContext.Provider>
  )
}

// 4. Make a hook to use the context easier
export const useMyContext = () => useContext(MyAppContext)

// 5. Use the context provider in some root (i.e: App.tsx)
// <MyContextProvider value={{...}}/>

// 6. Use hook to get and set context data
// const { foobar, setContext } = useMyContext()
// ...
/// setContext({ foobar: !foobar })
