import {useEffect, useMemo, useState} from 'react'
import {useRouter} from 'next/router'
import PropTypes from 'prop-types'
import {createTheme, ThemeProvider} from '@mui/material/styles'
import CssBaseline from '@mui/material/CssBaseline'
import {SessionProvider, useSession} from 'next-auth/react'
import {CacheProvider} from '@emotion/react'
import {grey, green, red} from '@mui/material/colors'
import NProgress from 'nprogress'
import createEmotionCache from '../lib/create-emotion-cache'

import '@fontsource/roboto/300.css'
import '@fontsource/roboto/400.css'
import '@fontsource/roboto/500.css'
import '@fontsource/roboto/700.css'
import '../styles/nprogress.css'

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

const getDesignTokens = mode => ({
  palette: {
    mode,
    ...(mode === 'light'
      ? {
        // Palette values for light mode
        primary: green,
        secondary: red,
        divider: green[200],
        text: {
          primary: grey[900],
          secondary: grey[800],
        },
      }
      : {
        // Palette values for dark mode
        primary: green,
        secondary: red,
        divider: green[700],
        background: {
          default: '#082211',
          paper: '#082211',
        },
        text: {
          primary: '#fff',
          secondary: grey[100],
        },
      }),
  },
})

const clientSideEmotionCache = createEmotionCache()

export default function MyApp(props) {
  const {Component, emotionCache = clientSideEmotionCache, pageProps} = props
  const [mode, setMode] = useState('light')
  const [switchFixed, setSwitchFixed] = useState(false)
  const theme = useMemo(() => createTheme(getDesignTokens(mode)), [mode])
  const router = useRouter()

  useEffect(() => {
    const handleStart = () => {
      NProgress.start()
    }

    const handleStop = () => {
      NProgress.done()
    }

    router.events.on('routeChangeStart', handleStart)
    router.events.on('routeChangeComplete', handleStop)
    router.events.on('routeChangeError', handleStop)

    return () => {
      router.events.off('routeChangeStart', handleStart)
      router.events.off('routeChangeComplete', handleStop)
      router.events.off('routeChangeError', handleStop)
    }
  }, [router])

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

  useEffect(() => {
    const oldLocalMode = localStorage.getItem('oki-dark')
    const localMode = localStorage.getItem('oki-theme')
    if (localMode === 'dark' || (oldLocalMode && oldLocalMode === 'true')) {
      setMode('dark')
    } else {
      setMode('light')
    }

    if (localMode && oldLocalMode) {
      localStorage.removeItem('oki-dark')
    }
  }, [])

  return (
    <CacheProvider value={emotionCache}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <SessionProvider session={pageProps.session} refetchInterval={5 * 60}>
          <SwitchTheme switchFixed={switchFixed} mode={mode} setMode={setMode} />
          {Component.auth ? (
            <Auth><Component {...pageProps} /></Auth>
          ) : (
            <Component {...pageProps} />
          )}
        </SessionProvider>
      </ThemeProvider>
    </CacheProvider>
  )
}

function Auth({children}) {
  const {data: session, status} = useSession()
  const loading = status === 'loading'
  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,
  emotionCache: PropTypes.object,
  router: PropTypes.object.isRequired
}

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