import { CssBaseline, List, Typography } from '@material-ui/core';
import { Home, Settings } from '@material-ui/icons';
import Protected from 'features/user/Protected';
import { AnimatePresence } from 'framer-motion';
import React, { useState } from 'react';
import { hot } from 'react-hot-loader/root';
import { Route, Switch, useLocation } from 'react-router-dom';
import styled from 'styled-components';
import { AdminLazy, HomeLazy } from 'views';
import NotFound from 'views/NotFound';

import ListItemLink from './components/ListLitemLink';
import NavDrawer from './components/NavDrawer';
import NavTitle from './components/NavTitle';
import TopBar from './components/TopBar';

export const Root = styled.div`
  display: flex;
`;

const drawerWidth = 240;
const App = () => {
  const [open, setOpen] = useState(false);
  const handleDrawerToggle = () => setOpen(!open);
  const location = useLocation();
  return (
    <Root>
      <CssBaseline />
      <TopBar onClick={handleDrawerToggle} drawerWidth={drawerWidth}>
        <AnimatePresence exitBeforeEnter initial={false}>
          <Switch location={location} key={location.pathname}>
            <Route exact path="/">
              <NavTitle>
                <Typography variant="h6" component="h1">
                  Home
                </Typography>
              </NavTitle>
            </Route>
            <Route exact path="/admin">
              <NavTitle>
                <Typography variant="h6" component="h1">
                  Admin Panel
                </Typography>
              </NavTitle>
            </Route>
            <Route>
              <NavTitle>
                <Typography variant="h6" component="h1">
                  Page Not Found
                </Typography>
              </NavTitle>
            </Route>
          </Switch>
        </AnimatePresence>
      </TopBar>
      <NavDrawer
        onClose={handleDrawerToggle}
        drawerWidth={drawerWidth}
        open={open}
      >
        <List>
          <ListItemLink icon={<Home />} primary="Home" to="/" />
          <Protected roles={['Admin']}>
            <ListItemLink icon={<Settings />} primary="Admin" to="/admin" />
          </Protected>
        </List>
      </NavDrawer>
      <AnimatePresence exitBeforeEnter initial={false}>
        <Switch location={location} key={location.pathname}>
          <Route exact path="/">
            <HomeLazy />
          </Route>
          <Route exact path="/admin">
            <Protected redirect="/" awaitAuth roles={['Admin']}>
              <AdminLazy />
            </Protected>
          </Route>
          <Route>
            <NotFound />
          </Route>
        </Switch>
      </AnimatePresence>
    </Root>
  );
};

export default process.env.NODE_ENV === 'development' ? hot(App) : App;
