import React, { lazy, Suspense, useEffect } from 'react'
import { Redirect, Route, RouteComponentProps, Switch, useHistory } from 'react-router'

import AppBar from '@agiliza/components/molecules/AppBar'
import CircularProgress from '@agiliza/components/molecules/CircularProgress'
import { actions as drawerActions } from '@agiliza/redux/ui/drawer'
import { actions as loginActions } from '@agiliza/redux/ui/login'
import { ProposalDataRouteState } from '@agiliza/views/ProposalData/pages/ProposalData'
import { Typography } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

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

const SimulationCreditLines = lazy(() => import('@agiliza/views/SimulationCreditLines/pages/router'))
const ProposalData = lazy(() => import('@agiliza/views/ProposalData/pages/ProposalData'))
const ListProjects = lazy(() => import('@agiliza/views/Projects/pages/ListProjects'))
// const SecurityProfile = lazy(() => import('@curio/ui/dist/views/SecurityProfile'))

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

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

const Main = (props: Props) => {
  const { classes, toggleDrawer, fetchMenu } = props

  const history = useHistory()

  useEffect(() => {
    fetchMenu()
  }, [])

  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} /> */}
      <Suspense fallback={<CircularProgress />}>
        <Switch>
          <Route path={PATHS.proposals} render={(rProps) => <ListProjects {...rProps} />} />
          <Route path={PATHS.simulation} render={(rProps) => <SimulationCreditLines {...rProps} />} />
          <Route
            path={PATHS.proposalData}
            render={(rProps) => {
              const { location } = rProps as RouteComponentProps<any, any, ProposalDataRouteState>
              // if (!location.state) location.state = { subproductId: '0' }
              if (location.state?.subproductId) return <ProposalData {...rProps} />
              else return <Redirect from={PATHS.proposalData} to="/" />
            }}
          />
          <Redirect from="/" to={PATHS.simulation} />
        </Switch>
      </Suspense>
    </div>
  )
}

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