import * as React from 'react'
import styled from 'styled-components'
import { Icon } from '../../../../react-common/src'

const ToggleWrapper = styled('label')({
  cursor: 'pointer',
  color: 'var(--color-accent)',
  display: 'inline-block',
})

const ToggleInput = styled('input')({
  position: 'absolute',
  left: -999999,
})

const getAutoDetectTheme = () => (
  window.matchMedia('(prefers-color-scheme: dark)').matches
    ? 'Dark'
    : 'Light'
)

const getTheme = () => window.localStorage.getItem('tesseract-theme') || getAutoDetectTheme()

const applyStyles = (theme) => {
  const stylesheets = Array.from(window.document.querySelectorAll('link[title]')) as HTMLLinkElement[]
  stylesheets.forEach(s => {
    const enabled = s.title === theme
    if (enabled) {
      s.setAttribute('rel', 'stylesheet')
      s.removeAttribute('disabled')
    } else {
      s.setAttribute('rel', 'alternate stylesheet')
      s.setAttribute('disabled', 'disabled')
    }
  })
}

const ThemeToggle = ({
  initialTheme,
}) => {
  const [enabled, setEnabled, ] = React.useState(false)
  const [theme, setTheme] = React.useState(null)

  const handleSetTheme = (e) => {
    setTheme(e.target.checked ? 'Light' : 'Dark')
  }

  React.useEffect(() => {
    if (theme as string) {
      window.localStorage.setItem('tesseract-theme', theme)
      return
    }
    window.setTimeout(() => {
      setTheme(getTheme())
    })
  }, [theme])

  React.useEffect(() => {
    if (theme as string) {
      applyStyles(theme)
    }
  }, [theme])

  React.useEffect(() => {
    setEnabled(true)
  }, [])

  if (enabled) {
    return (
      <ToggleWrapper>
        <ToggleInput
          type="checkbox"
          checked={theme === 'Light'}
          onChange={handleSetTheme}
        />
        <span>
          <Icon
            label="Toggle Theme"
            name={theme === 'Dark' ? 'moon' : 'sun'}
          />
        </span>
      </ToggleWrapper>
    )
  }

  return null
}

export default ThemeToggle
