import { createHashHistory } from 'history'
import React, { lazy, Suspense, useEffect } from 'react'
import { connect } from 'react-redux'
import { Route, Router, Switch } from 'react-router'
import { bindActionCreators, Dispatch } from 'redux'

import CircularProgress from '@agiliza/components/molecules/CircularProgress'
import { StoreState } from '@agiliza/redux'
import { isAuthenticated, isAuthenticating, isInitializing } from '@agiliza/redux/session/selectors'
import { actions as drawerActions } from '@agiliza/redux/ui/drawer'
import { isDrawerOpen } from '@agiliza/redux/ui/drawer/selectors'
import { getError } from '@agiliza/redux/ui/error/selectors'
import { actions as loginActions } from '@agiliza/redux/ui/login'

// import Login from './Login'

const Main = lazy(() => import('./Main'))

const history = createHashHistory()

interface Props {
  error: string
  authenticated: boolean
  authenticating: boolean
  connect: typeof loginActions.connect
}

const Views = (props: Props) => {
  const { authenticating } = props

  useEffect(() => {
    // props.connect()
  }, [])

  if (authenticating) return <CircularProgress root />

  return (
    <Router history={history}>
      <Suspense fallback={<CircularProgress />}>
        <Switch>
          {/* <Route path="/login" render={(renderProps) => <Login {...renderProps} />} /> */}
          <Route path="/" component={Main} />
          {/* <AuthRoute path="/" component={Main} /> */}
        </Switch>
      </Suspense>
    </Router>
  )
}

const mapStateToProps = (state: StoreState) => ({
  error: getError(state.ui.error),
  authenticated: isAuthenticated(state.session),
  authenticating: isAuthenticating(state.session) || isInitializing(state.session),
  drawerOpen: isDrawerOpen(state.ui.drawer),
})

const mapDispatchToProps = (dispatch: Dispatch) =>
  bindActionCreators(
    {
      toggleDrawer: drawerActions.toggleDrawer,
      connect: loginActions.connect,
    },
    dispatch
  )

export default connect(mapStateToProps, mapDispatchToProps)(Views)
