import { ThemeProvider } from '@material-ui/core'
import Navbar from 'components/Navbar/Navbar'
import AppRoutes from 'components/Routes/Routes'
import SplashRoot from 'components/Splash/SplashRoot'
import WelcomeModal from 'components/WelcomeModal/WelcomeModal'
import { useWebviewIntent } from 'cozy-intent'
import { Layout } from 'cozy-ui/transpiled/react/Layout'
import React, { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useAppSelector } from 'store/hooks'
import MatomoTracker from 'utils/matomoTracker'
import { theme } from './theme'

interface AppProps {
  tracker: undefined | MatomoTracker
}

export const App = ({ tracker }: AppProps) => {
  const location = useLocation()
  const {
    global: { termsStatus },
    profile: { onboarding },
  } = useAppSelector(state => state.ecolyo)
  const webviewIntent = useWebviewIntent()

  useEffect(() => {
    tracker?.track(location)
  }, [tracker, location])

  useEffect(() => {
    webviewIntent?.call('setFlagshipUI', {
      bottomBackground: '#32343d',
      bottomTheme: 'light',
      topBackground: '#1b1c22',
      topTheme: 'light',
    })
  }, [webviewIntent])

  return (
    <Layout>
      <ThemeProvider theme={theme}>
        <SplashRoot>
          {termsStatus.accepted && (
            <>
              <WelcomeModal open={!onboarding.isWelcomeSeen} />
              <Navbar />
            </>
          )}
          <main className="app-content">
            <AppRoutes termsStatus={termsStatus} />
          </main>
        </SplashRoot>
      </ThemeProvider>
    </Layout>
  )
}

export default App