import React from 'react'
import Cookies from 'js-cookie'

const CookiesContext = React.createContext(null)

export function useCookies() {
  const cookies = React.useContext(CookiesContext)
  if (!cookies)
    throw new Error('Please make sure CookiesContextProvider is available')
  return cookies
}

export function CookiesContextProvider({ children }) {
  const cookies = useRawCookies()
  return (
    <CookiesContext.Provider value={cookies}>
      {children}
    </CookiesContext.Provider>
  )
}

function useRawCookies() {
  const [cookies, setCookies] = React.useState(() => Cookies.get() || {})

  function get(name) {
    return cookies[name]
  }

  function set(name, value, options) {
    setCookies({ ...cookies, [name]: value })
    Cookies.set(name, value, options)
  }

  function remove(name, options) {
    const { [name]: _, ...otherCookies } = cookies
    setCookies(otherCookies)
    Cookies.remove(name, options)
  }

  return [get, set, remove, cookies]
}
