import React from 'react';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import List from '@material-ui/core/List';
import CssBaseline from '@material-ui/core/CssBaseline';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ExpandMore from '@material-ui/icons/ExpandMore'
import ExpandLess from '@material-ui/icons/ExpandLess'
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
import Collapse from '@material-ui/core/Collapse';
import DateFnsUtils from '@date-io/date-fns';
import { DateTimePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import localeID from 'date-fns/locale/id';

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams,
  useRouteMatch
} from "react-router-dom";
import Images from '../assets/Images';
import { FadeMenu, Footer, UseWindowDimensions } from '../Utils/Index';
import Beranda from './Beranda';
import { Avatar } from '@material-ui/core';
import HomeRoutes from '../router/homeRoutes'
import ArraySide from '../library/Array'
import Constant from '../library/Constant';
import api from '../api';

const drawerWidth = 307;


const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
  },
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  appBarShift: {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
  },
  menuButton: {
    marginRight: 36,
  },
  hide: {
    display: 'none',
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
  },
  drawerOpen: {
    width: drawerWidth,
    borderRight: 0,
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
    backgroundColor: '#f6f7f9'
  },
  drawerClose: {
    borderRight: 0,
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    overflowX: 'hidden',
    width: theme.spacing(3) + 2,
    [theme.breakpoints.up('sm')]: {
      width: theme.spacing(7) + 1,
    },
    backgroundColor: '#f6f7f9'
  },
  toolbar: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
  },
  toolbarDrawer: {
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    // ...theme.mixins.toolbar
  },
  content: {
    flexGrow: 1,
    padding: theme.spacing(3),
  },
  orangeAvatar: {
    margin: 10,
    color: '#fff',
    backgroundColor: 'black',
  },
}));

export default function MiniDrawer() {
  const classes = useStyles();
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);
  const [selectedIndex, setSelectedIndex] = React.useState([]);
  const [selectedIndexs, setSelectedIndexs] = React.useState([]);
  const [selectedSubIndex, setSelectSub] = React.useState([]);
  const [userFullname, setUserFullname] = React.useState("")
  const [userEmail, setUserEmail] = React.useState("")

  React.useEffect(() => {
    if (userFullname == "" && userEmail == "") {
      getUserData()
    }
  })

  const getUserData = () => {
    let userId = localStorage.getItem(Constant.USER)
    api.create().getDetailUser(userId).then((response) => {
      if (response.data.status == 'success') {
        setUserFullname(response.data.data.fullname == null ? 'Anonym' : response.data.data.fullname)
        setUserEmail(response.data.data.email == null ? 'Anonym@123.xyz' : response.data.data.email)
        console.log(userEmail)
      }
    })
  }

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  const resetIndex = () => {
    setSelectedIndex("")
    setSelectedIndexs("")
  }

  const selectSub = (e) => {
    setSelectSub(e)
    setSelectedIndex("")
  }

  const selectIndex = (e) => {
    setSelectSub("")
    setSelectedIndex(e)
  }

  const logout = () => {  
    localStorage.removeItem(Constant.TOKEN)
    window.location.reload();
  }

  let { path, url } = useRouteMatch();

  const { height, width } = UseWindowDimensions();

  return (
    <div className={classes.root}>
      <CssBaseline />
      <AppBar
        position="fixed"
        className={clsx(classes.appBar, {
          [classes.appBarShift]: open,
        })}
      >
      </AppBar>
      <Drawer
        variant="permanent"
        className={clsx(classes.drawer, {
          [classes.drawerOpen]: open,
          [classes.drawerClose]: !open,
        })}
        classes={{
          paper: clsx({
            [classes.drawerOpen]: open,
            [classes.drawerClose]: !open,
          }),
        }}
      >
        <div className={classes.toolbarDrawer} style={{
          backgroundColor: '#1a2d3e',
          height: open ? 203 : 78,
          paddingLeft: open ? null : 55,
          display: open ? null : 'grid',
          alignSelf: open ? null : 'center'
        }}>
          {open === true ?

            <div style={{ display: 'flex', justifyContent: 'space-between', flex: 1, padding: 10 }}>
              <img src={Images.triputra} alt="React Logo" style={{ height: 31, width: 151, alignSelf: 'center' }} />
              <IconButton onClick={handleDrawerClose} style={{ outline: 'none' }}>
                <ChevronLeftIcon style={{ fill: 'white' }} />
              </IconButton>
            </div> :
            <IconButton
              color="inherit"
              aria-label="open drawer"
              style={{ outline: 'none' }}
              onClick={handleDrawerOpen}
              edge="start"
              className={clsx(classes.menuButton, {
                [classes.hide]: open,
              })}
            >
              <MenuIcon style={{ fill: 'white' }} />
            </IconButton>}
          {open &&
            <div style={{ width: '100%', marginTop: 15, marginBottom: 60 }}>
              <Typography style={{ fontSize: 14, color: '#fff', textAlign: 'center', fontWeight: 'bold' }}>{userFullname}</Typography>
              <Typography style={{ fontSize: 14, color: '#fff', textAlign: 'center', marginTop: 10 }}>{userEmail}</Typography>
            </div>
          }
        </div>
        <Divider />
        {open &&
          <div style={{ width: '100%', textAlign: '-webkit-center', marginTop: -45 }}>
            <div className={"sub-color"} style={{ width: 90, height: 90, borderRadius: 50, display: 'flex', justifyContent: 'center' }}>
              <div style={{ width: 72, height: 72, backgroundColor: '#838383', borderRadius: 50, alignSelf: 'center' }}>
              </div>

            </div>
          </div>
        }
        {open &&
          <div style={{ marginLeft: 20, marginTop: 10 }}>
            <Typography style={{ color: '#525355', fontSize: 14, fontFamily: 'nunito' }}>Application</Typography>
          </div>
        }
        <List>
          {ArraySide.map((item, index) => (
            <div style={{ marginTop: index === 0 ? null : 5 }} >
              {item.subItem != null ?
                <div style={{ justifyContent: 'space-between', flexDirection: 'row', display: 'flex', paddingLeft: 5, paddingRight: 10 }} onClick={() => selectedIndexs == null ? setSelectedIndexs(item.label) : setSelectedIndexs(null)}>
                  <ListItem key={item.label}>
                    <ListItemIcon style={{ minWidth: open ? 40 : 56 }}><img src={item.img} /></ListItemIcon>
                    <Typography style={{ fontFamily: 'nunito', color: '#525355', fontSize: 14 }}>{item.label}</Typography>
                  </ListItem>
                  {item.subItem != null ? (item.label === selectedIndex ? <ExpandLess style={{ color: "#525355", marginLeft: 50, alignSelf: 'center' }} /> : <ExpandMore style={{ color: "#525355", marginLeft: 50, alignSelf: 'center' }} />) : null}
                </div>
                :
                item.label === 'Settings' ?
                  open ?
                    <Link to={`${url}/${item.path}`}>
                      <ListItem button key={item.label} onClick={() => null}>
                        <Typography style={{ color: '#525355', fontSize: 14, fontFamily: 'nunito' }}>{item.label}</Typography>
                      </ListItem>
                    </Link> : null
                  :
                  <Link to={`${url}/${item.path}`}>
                    <div style={{ paddingLeft: 5 }} className={selectedIndex === item.label ? "active" : ""}>
                      <ListItem button key={item.label} onClick={() => selectIndex(item.label)}>
                        <ListItemIcon style={{ minWidth: open ? 40 : 56 }}><img src={item.img} style={{ fill: '#525355' }} /></ListItemIcon>
                        <Typography style={{ fontFamily: 'nunito', color: '#525355', fontSize: 14 }}>{item.label}</Typography>
                      </ListItem>
                    </div>
                  </Link>
              }
              {item.subItem != null &&
                <div>
                  <Collapse in={item.label === selectedIndexs} timeout="auto" unmountOnExit>
                    <List component="div" disablePadding>
                      {item.subItem.map((sub, indexs) => {
                        return (
                          <Link to={`${url}/${sub.path}`}>
                            <div style={{ paddingLeft: 5, }} className={selectedSubIndex === sub.label ? "active" : ""} onClick={() => sub.label === "Logout" ? logout() : selectSub(sub.label)}>
                              <ListItem button style={{ paddingLeft: 61 }}>
                                <Typography style={{ fontFamily: 'nunito', color: '#525355', fontSize: 14 }}>{sub.label}</Typography>
                              </ListItem>
                            </div>
                          </Link>
                        )
                      })}
                    </List>
                  </Collapse>
                </div>
              }
            </div>
          ))}
        </List>
      </Drawer>
      <div className={classes.content} style={{ justifyContent: 'space-between', padding: 0, backgroundColor: '#f8f8f8' }}>
        <div>
          {/* <div className={classes.toolbar} /> */}
          <MuiPickersUtilsProvider locale={localeID} utils={DateFnsUtils}>
            <Switch>
              {HomeRoutes.map((route, index) => (
                // You can render a <Route> in as many places
                // as you want in your app. It will render along
                // with any other <Route>s that also match the URL.
                // So, a sidebar or breadcrumbs or anything else
                // that requires you to render multiple things
                // in multiple places at the same URL is nothing
                // more than multiple <Route>s.
                <Route
                  key={index}
                  path={route.path}
                  // exact={route.exact}
                  children={<route.main height={height} />}
                />
              ))}
            </Switch>
          </MuiPickersUtilsProvider>
          {/* <Footer>
            <Typography style={{ fontSize: '12px' }}>© EKSAD Technology. All rights reserved.</Typography>
          </Footer> */}
        </div>

      </div>
    </div>
  );
}