import React, { Suspense } from 'react';
import PropTypes from 'prop-types';
import { Route, Switch, withRouter } from 'react-router-dom';
import * as router from 'react-router-dom';
import { Container } from 'reactstrap';
import {
  AppFooter,
  AppHeader,
  AppSidebar,
  AppSidebarFooter,
  AppSidebarForm,
  AppSidebarHeader,
  AppSidebarMinimizer,
  AppSidebarNav2 as AppSidebarNav,
  AppBreadcrumb2 as AppBreadcrumb
} from '@coreui/react';
import { Page404 } from "../../pages"

const BackendFooter = React.lazy(() => import('./BackendFooter'));
const BackendHeader = React.lazy(() => import('./BackendHeader'));

function BackendTemplate({ ...props }) {
  const loading = () => <div className="animated fadeIn pt-1 text-center">Loading...</div>
  const parentProps = props

  return (
    <div className="app">
      <AppHeader fixed>
        <Suspense fallback={loading()}>
          <BackendHeader {...props} />
        </Suspense>
      </AppHeader>
      <div className="app-body">
        <AppSidebar fixed display="lg">
          <AppSidebarHeader />
          <AppSidebarForm />
          <Suspense>
            <AppSidebarNav navConfig={props.navConfig} {...props} router={router} />
          </Suspense>
          <AppSidebarFooter />
          <AppSidebarMinimizer />
        </AppSidebar>
        <main className="main">
          {props.history.location.key && <AppBreadcrumb appRoutes={props.routeConfig} router={router} />}
          <Container fluid>
            <Suspense fallback={loading()}>
              <Switch>
                {props.routeConfig.map((route, idx) => {
                  return route.component ? (
                    <Route
                      key={idx}
                      path={route.path}
                      exact={route.exact}
                      name={route.name}
                      render={props => <route.component {...props} {...parentProps} />} />
                  ) : null;
                })}
                <Route render={() => (
                  <div style={{ display: 'flex', flex: 1, height: '88.5vh', justifyContent: 'center', alignItems: 'center' }}>
                    <Page404 includeTemplate={false} />
                  </div>
                )} />              
              </Switch>
            </Suspense>
          </Container>
        </main>
      </div>
      <AppFooter>
        <Suspense fallback={loading()}>
          <BackendFooter {...props} />
        </Suspense>
      </AppFooter>
    </div>
  );
}
export default withRouter(BackendTemplate)

BackendTemplate.propTypes = {
  routeConfig: PropTypes.oneOfType([PropTypes.array.isRequired, PropTypes.object.isRequired]),
  navConfig: PropTypes.oneOfType([PropTypes.array.isRequired, PropTypes.object.isRequired])
}
BackendTemplate.defualtProps = {
  routeConfig: [],
  navConfig: []
}

