import React, { lazy, Suspense } from 'react'
import { SkeletonTheme } from 'react-loading-skeleton'
import { Redirect, Route, RouteComponentProps, Switch } from 'react-router'

import AppBar from '@agiliza/components/molecules/AppBar'
import CircularProgress from '@agiliza/components/molecules/CircularProgress'
import Drawer from '@agiliza/components/molecules/Drawer'
import { actions as drawerActions } from '@agiliza/redux/ui/drawer'
import { Typography } from '@material-ui/core'
import { useTheme, withStyles, WithStyles } from '@material-ui/core/styles'

import connect, { ConnectedProps } from './connect'
import DrawerItems, { PATHS } from './DrawerItems'
import styles from './styles'

const Dashboard = lazy(() => import('../Dashboard'))
const Projects = lazy(() => import('@agiliza/views/Projects/pages/Searcher'))

type BaseProps = RouteComponentProps & ConnectedProps & WithStyles<typeof styles>

interface Props extends BaseProps {
  toggleDrawer: typeof drawerActions.toggleDrawer
}

const Main = (props: Props) => {
  const theme = useTheme()
  const { classes, drawerOpen, toggleDrawer, logout, ...routeProps } = props

  const { history } = routeProps

  return (
    <div className={classes.pageContainer}>
      <AppBar
        onNavClick={toggleDrawer}
        title={
          <a onClick={() => history.push('/')} className={classes.titleAnchor}>
            <Typography className={classes.appTitle}>Agiliza</Typography>
          </a>
        }
      />
      <Drawer drawerOpen={drawerOpen} toggleDrawer={toggleDrawer} logout={logout} Items={DrawerItems} {...routeProps} />
      <SkeletonTheme color={theme.palette.grey[500]} highlightColor={theme.palette.grey[300]}>
        <Suspense fallback={<CircularProgress />}>
          <Switch>
            <Route path={PATHS.dashboard} render={() => <Dashboard />} />
            <Route path={PATHS.projects} render={() => <Projects />} />
            <Redirect from="/" to={PATHS.projects} />
          </Switch>
        </Suspense>
      </SkeletonTheme>
    </div>
  )
}

export default connect(withStyles(styles)(Main))
