import { Classes } from '@blueprintjs/core'
import Keys from '@inject/shared/localstorage/keys'
import { makeVar, useReactiveVar } from '@inject/shared/utils/reactive'

const getDarkmode = () => {
  const val = localStorage.getItem(Keys.DARK_MODE)
  if (val) {
    return val === 'true'
  }
  return (
    window.matchMedia &&
    window.matchMedia('(prefers-color-scheme: dark)').matches
  )
}

const initialSettings: boolean = getDarkmode()

export const colormode = makeVar<boolean | null>(initialSettings)
export const useColormode = () => useReactiveVar(colormode)

function changeColor(value: boolean) {
  if (value) {
    document.body.classList.add(Classes.DARK)
  } else {
    document.body.classList.remove(Classes.DARK)
  }
}

window.addEventListener('storage', ({ key, newValue, oldValue }) => {
  if (key === Keys.DARK_MODE && newValue !== oldValue) {
    changeColor(getDarkmode())
    colormode(getDarkmode())
  }
})

window
  .matchMedia('(prefers-color-scheme: dark)')
  .addEventListener('change', () => {
    changeColor(getDarkmode())
  })

changeColor(initialSettings)
colormode.onNextChange(function onNext(value: boolean | null) {
  if (value === null) {
    localStorage.removeItem(Keys.DARK_MODE)
  } else {
    localStorage.setItem(Keys.DARK_MODE, value.toString())
  }
  changeColor(getDarkmode())
  colormode.onNextChange(onNext)
})
