import { Button, Icon, Switch } from '@blueprintjs/core'
import { useEffect, useMemo, useState } from 'react'
import SettingsSection from '../SettingsSection'
import { colormode, useColormode } from '../vars/colormode'

const ColorMode = () => {
  const darkValue = useColormode()
  const [val, setVal] = useState<boolean>(true)

  const dark = useMemo(
    () =>
      darkValue === null
        ? window.matchMedia('(prefers-color-scheme: dark)').matches
        : darkValue,
    [darkValue, val]
  )

  const event: (ev: MediaQueryListEvent) => void = ev => {
    setVal(ev.matches)
  }

  useEffect(() => {
    window
      .matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', event)
    return () =>
      window
        .matchMedia('(prefers-color-scheme: dark)')
        .removeEventListener('change', event)
  })

  return (
    <SettingsSection
      title='Color mode'
      subtitle='Change the color mode of the application'
    >
      <Icon icon={dark ? 'moon' : 'circle'} />
      <Switch
        style={{ margin: 0 }}
        checked={dark}
        title='Toggle color mode'
        onChange={() => colormode(!dark)}
      />
      <Button
        icon='reset'
        minimal
        onClick={() => colormode(null)}
        title='Reset to automatic color mode'
      />
    </SettingsSection>
  )
}

export default ColorMode
