import { Button, Icon, Switch } from '@blueprintjs/core'
import type { FC } from 'react'
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 const ColorModeMini: FC<{ fill?: boolean }> = ({ fill }) => {
  const darkValue = useColormode()
  return (
    <Button
      icon={darkValue ? 'moon' : 'circle'}
      alignText='center'
      fill={fill}
      minimal
      title='Switch light mode'
      onClick={() => colormode(!darkValue)}
    />
  )
}

export default ColorMode
