import React, {useEffect, useMemo, useState} from 'react'
import {useRouter} from 'next/router'
import PropTypes from 'prop-types'
import {createMuiTheme, ThemeProvider, makeStyles} from '@material-ui/core/styles'
import CssBaseline from '@material-ui/core/CssBaseline'
import {Provider, useSession} from 'next-auth/client'
import {Box} from '@material-ui/core'

import SwitchTheme from '../components/switch-theme'

const useStyles = makeStyles({
  switch: {
    position: 'absolute',
    right: '1em',
    top: '95px',
    zIndex: 1,
    cursor: 'pointer'
  },
  switchFixed: {
    position: 'fixed',
    right: '1em',
    top: '95px',
    zIndex: 9990,
    cursor: 'pointer'
  }
})

export default function MyApp(props) {
  const {Component, pageProps} = props
  const [darkMode, setDarkMode] = useState(true)
  const [switchFixed, setSwitchFixed] = useState(false)
  const classes = useStyles()

  const darkTheme = useMemo(() => createMuiTheme({
    palette: {
      type: darkMode ? 'dark' : 'light',
      primary: {
        light: '#81c784',
        main: '#4caf50',
        dark: '#388e3c',
        contrastText: '#fff'
      }
    }
  }), [darkMode])

  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side')
    if (jssStyles) {
      jssStyles.remove()
    }
  }, [])

  useEffect(() => {
    if (props.router.pathname.slice(0, 5) === '/teks') {
      setSwitchFixed(true)
    } else {
      setSwitchFixed(false)
    }
  }, [props])

  useEffect(() => {
    const dark = localStorage.getItem('oki-dark')
    if (dark === 'false') {
      setDarkMode(false)
    } else {
      setDarkMode(true)
    }
  }, [])

  return (
    <ThemeProvider theme={darkTheme}>
      <CssBaseline />
      <Provider session={pageProps.session}>
        <Box className={switchFixed ? classes.switchFixed : classes.switch}>
          <SwitchTheme darkMode={darkMode} setDarkMode={setDarkMode} />
        </Box>
        {Component.auth ? (
          <Auth><Component {...pageProps} /></Auth>
        ) : (
          <Component {...pageProps} />
        )}
      </Provider>
    </ThemeProvider>
  )
}

function Auth({children}) {
  const [session, loading] = useSession()
  const isUser = Boolean(session?.user)
  const router = useRouter()
  useEffect(() => {
    if (loading) {
      return
    }

    if (!isUser) {
      router.push('/soumet')
    }
  }, [isUser, loading, router])

  if (isUser) {
    return children
  }

  return (
    <div>Loading...</div>
  )
}

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  pageProps: PropTypes.object.isRequired,
  router: PropTypes.object.isRequired
}

Auth.propTypes = {
  children: PropTypes.node.isRequired
}
