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

import { PATHS } from '@agiliza/views/Main/DrawerItems'
import { CircularProgress } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import styles from './shared-styles'

const CreditLinesList = lazy(() => import('./CreditLinesList'))
const Simulation = lazy(() => import('./Simulation'))
const FinishSimulation = lazy(() => import('./FinishSimulation'))

export const CREDIT_LINES_PATHS = {
  creditLinesList: PATHS.simulation + '/selecionarLinhaCredito',
  simulation: PATHS.simulation + '/simulador',
  finishSimulation: PATHS.simulation + '/finalizarSimulacao',
}

export interface SimulationRouteState {
  hasSubproducts: boolean
}

export interface FinishSimulationRouteState {
  proposalId: boolean
}

type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps

interface Props extends ExtendedProps {}

const CreditLinesRouter = (props: Props) => {
  const { classes, match } = props
  return (
    <div className={classes.pageContent}>
      <Suspense fallback={<CircularProgress className={classes.circularProgress} />}>
        <Switch>
          <Route exact path={CREDIT_LINES_PATHS.creditLinesList} render={(rProps) => <CreditLinesList {...rProps} />} />
          <Route
            exact
            path={CREDIT_LINES_PATHS.simulation}
            render={(rProps) => {
              const { location } = rProps as RouteComponentProps<any, any, SimulationRouteState>
              if (location.state?.hasSubproducts) return <Simulation {...rProps} />
              else return <Redirect from={CREDIT_LINES_PATHS.simulation} to="/" />
            }}
          />
          <Route
            exact
            path={CREDIT_LINES_PATHS.finishSimulation}
            render={(rProps) => {
              const { location } = rProps as RouteComponentProps<any, any, FinishSimulationRouteState>
              if (location.state?.proposalId) return <FinishSimulation {...rProps} />
              else return <Redirect from={match.path + CREDIT_LINES_PATHS.simulation} to="/" />
            }}
          />
          <Redirect from={match.path} to={CREDIT_LINES_PATHS.creditLinesList} />
        </Switch>
      </Suspense>
    </div>
  )
}

export default withStyles(styles)(CreditLinesRouter)
