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 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 ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import Collapse from '@material-ui/core/Collapse';
import DateFnsUtils from '@date-io/date-fns';
import { MuiPickersUtilsProvider } from "@material-ui/pickers";
import localeID from 'date-fns/locale/en-US';
import ReactTooltip from 'react-tooltip';

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams,
  useRouteMatch, useLocation
} 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',
  },
  topleftOpen: {
    width: drawerWidth,
    borderRight: 0,
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
    backgroundColor: '#273b80'
  },
  topleftClose: {
    borderRight: 0,
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    overflowX: 'hidden',
    width: theme.spacing(3) + 2,
    height: '78px',
    [theme.breakpoints.up('sm')]: {
      width: theme.spacing(7) + 1,
    },
    padding: 20,
    display: 'flex',
    backgroundColor: '#273b80'
  },
  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() {
  let location = useLocation();
  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("")
  const [userPhoto, setUserPhoto] = React.useState("")
  const [application, setApplication] = React.useState([])
  const [setting, setSetting] = React.useState([])
  const [data, setData] = React.useState({
    array: [
      {
        img: Images.Home,
        label: 'Home',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.budgetTahunan,
        label: 'Master Budget & CAT',
        path: 'budget-tahunan',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.laporanBulanan,
        label: 'Monthly Report',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.rolling,
        label: 'Rolling Outlook & CAT Revision',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.outlookperformance,
        label: 'Outlook Performance Appraisal',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.operatingindicator,
        label: 'Operating Indicator',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.manajemenDokumen,
        label: 'Document Management',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.laporan,
        label: 'Reports',
        path: '',
        subItem: [
          {
            img: 'beranda',
            label: 'CAT Dashboard',
            path: 'dashboard-cat',
          },
          {
            img: 'beranda',
            label: 'Summary of Triputra Group',
            path: 'beranda',
          },
          {
            img: '',
            label: 'Sub Holding',
            path: 'beranda',
          }
        ],
        collapse: false,
      },
      {
        img: '',
        label: 'Settings',
        path: 'beranda',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.masterdata,
        label: 'Master Data',
        path: '',
        subItem: [
          {
            img: '',
            label: 'Business Unit',
            path: 'unit-bisnis',
          },
          {
            img: '',
            label: 'Company',
            path: 'perusahaan',
          },
          {
            img: '',
            label: 'Report Items',
            path: 'report-items',
          },
          {
            img: '',
            label: 'Parameters',
            path: 'parameter',
          },
        ],
        collapse: false,
      },
      {
        img: Images.otorisasi,
        label: 'Authorization',
        path: '',
        subItem: [
          {
            img: '',
            label: 'User Role',
            path: 'userrole',
          },
          {
            img: '',
            label: 'User',
            path: 'user',
          }
        ],
        collapse: false,
      },
      {
        img: Images.approvalmatrix,
        label: 'Approval Matrix',
        path: 'approval-matrix',
        subItem: null,
        collapse: false,
      },
      {
        img: Images.otorisasi,
        label: 'User Management',
        path: '',
        subItem: [
          {
            img: '',
            label: 'Profile',
            path: 'profile',
          },
          {
            img: '',
            label: 'Logout',
            path: '',
          },
        ],
        collapse: false,
      }
    ]
  })

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

  const parseChildren = (val) => {
    let data = Object.assign([], val)
    data = data.sort((a, b) => a.menu_id - b.menu_id).map((i) => {
      return {
        img: i.icon === '#' ? "" : i.icon,
        label: i.menu_name,
        path: i.url,
        subItem: parseChildren(i.sub_menu),
        collapse: false
      }
    })
    return data
  }

  const getMenuHierarki = () => {
    api.create().getMenuByRole().then((response) => {
      console.log(response)
      if (response.data) {
        if (response.data.status === "success") {
          let app = null
          let set = null
          response.data.data.map((item) => {
            if (item.menu_name === "Application") {
              app = parseChildren(item.sub_menu)
              return app
            } else {
              set = parseChildren(item.sub_menu)
              return set
            }
          })
          setApplication(app)
          setSetting(set)
          console.log(set);
        } else {
          localStorage.removeItem(Constant.TOKEN)
          window.location.reload();
        }
      } else {
        localStorage.removeItem(Constant.TOKEN)
        window.location.reload();
      }
    })
  }

  const getUserData = () => {
    let userId = localStorage.getItem(Constant.USER)
    api.create().getDetailUser(userId).then((response) => {
      if (response.data) {
        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)
          setUserPhoto(response.data.data.photo === null ? "" : response.data.data.photo)
        }
      }
    })
  }

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

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

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

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

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

  const selectIndex = (e) => {
    setSelectSub("")
    setSelectedIndex(e)
    // alert(e)
    // if (open === false) {
    // setOpen(true)
    // }
  }

  let { path, url } = useRouteMatch();

  const { height, width } = UseWindowDimensions();

  function handleCollapse(item) {
    setOpen(true);
    let arr = application
    let index = arr.findIndex((val) => val.label === item.label)
    arr[index].collapse = !arr[index].collapse
    setData({ ...application, application: arr })
  }

  function handleCollapseSetting(item) {
    setOpen(true);
    let arr = setting
    let index = arr.findIndex((val) => val.label === item.label)
    arr[index].collapse = !arr[index].collapse
    setData({ ...setting, setting: arr })
  }

  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={clsx(classes.drawer, {
          [classes.topleftOpen]: open,
          [classes.topleftClose]: !open,
        })}
          classes={{
            paper: clsx({
              [classes.topleftOpen]: open,
              [classes.topleftClose]: !open,
            }),
          }}>
          {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', marginLeft: 5 }} />
              <IconButton onClick={handleDrawerClose} style={{ outline: 'none' }}>
                <MenuIcon 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,
              })}
            >

              <a data-tip={"Main Menu"} data-for={"main-menu"}>
                <MenuIcon style={{ fill: 'white', alignSelf: 'center' }} />
              </a>
              <ReactTooltip border={true} id={"main-menu"} place="bottom" type="light" effect="solid" />
            </IconButton>}
          {open &&
            <div style={{ width: '100%', marginTop: 15, marginBottom: 60 }}>
              <Link to={"profile"}>
                <Typography style={{ fontSize: 14, color: '#fff', textAlign: 'center', fontWeight: 'bold' }}>{userFullname}</Typography>
              </Link>
              <Link to={"profile"}>
                <Typography style={{ fontSize: 14, color: '#fff', textAlign: 'center', marginTop: 10 }}>{userEmail}</Typography>
              </Link>
            </div>
          }
        </div>
        <Divider />
        {open &&
          <div style={{ width: '100%', textAlign: '-webkit-center', marginTop: -45, display: 'flex', justifyContent: 'center' }}>
            <Link to={"profile"}>
              <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' }}>
                  {userPhoto === "" ? null : <img src={userPhoto} style={{ width: 72, height: 72, borderRadius: 50 }} />}
                </div>
              </div>
            </Link>
          </div>
        }
        {open && application.length > 0 &&
          <div style={{ marginLeft: 20, marginTop: 10 }}>
            <Typography style={{ color: '#525355', fontSize: 14, fontFamily: 'Nunito Sans, sans-serif' }}>Application</Typography>
          </div>
        }
        <List>
          {application.map((item, index) => (
            <div style={{ marginTop: index === 0 ? null : 5 }} >
              {item.subItem.length !== 0 ?
                <a data-tip={item.label} data-for={item.label}>
                  <div style={{ justifyContent: 'space-between', flexDirection: 'row', display: 'flex', paddingLeft: 5, paddingRight: 10, cursor: 'pointer' }} onClick={() => { handleCollapse(item) }}>
                    <ListItem key={item.label}>
                      <ListItemIcon style={{ minWidth: open ? 40 : 56 }}><img src={item.img} /></ListItemIcon>
                      <Typography style={{ fontFamily: 'Nunito Sans, sans-serif', color: '#525355', fontSize: 14 }}>{item.label}</Typography>
                    </ListItem>
                    {item.subItem.length !== 0 ? (item.collapse ? <ExpandLess style={{ color: "#525355", marginLeft: 50, alignSelf: 'center' }} /> : <ExpandMore style={{ color: "#525355", marginLeft: 50, alignSelf: 'center' }} />) : null}
                    {!open && (<ReactTooltip border={true} id={item.label} place="bottom" type="light" effect="solid" />)}
                  </div>
                </a>
                :
                <Link to={`${url}/${item.path}`}>
                  <div style={{ paddingLeft: 5 }} className={selectedIndex === item.label ? "active" : ""}>
                    <a data-tip={item.label} data-for={item.label}>
                      <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 Sans, sans-serif', color: '#525355', fontSize: 14 }}>{item.label}</Typography>
                      </ListItem>
                    </a>
                    {!open && (<ReactTooltip border={true} id={item.label} place="bottom" type="light" effect="solid" />)}
                  </div>
                </Link>
              }
              {item.subItem.length !== 0 &&
                <div>
                  <Collapse in={item.collapse} timeout="auto" unmountOnExit>
                    <List component="div" disablePadding>
                      {item.subItem.map((sub, indexs) => {
                        return (
                          <Link to={sub.label === "Logout" ? `/` : `${url}/${sub.path}`}>
                            <a data-tip={sub.label} data-for={sub.label}>
                              <div style={{ paddingLeft: 5, }} className={selectedSubIndex === sub.label ? "active" : ""} onClick={() => sub.label === "Logout" ? logout() : selectSub(sub.label)}>
                                <ListItem button style={{ paddingLeft: 57 }}>
                                  <Typography style={{ fontFamily: 'Nunito Sans, sans-serif', color: '#525355', fontSize: 14 }}>{sub.label}</Typography>
                                </ListItem>
                              </div>
                            </a>
                            {!open && (<ReactTooltip border={true} id={sub.label} place="bottom" type="light" effect="solid" />)}
                          </Link>
                        )
                      })}
                    </List>
                  </Collapse>
                </div>
              }
            </div>
          ))}
        </List>
        {open && setting.length > 0 &&
          <div style={{ marginLeft: 20 }}>
            <Typography style={{ color: '#525355', fontSize: 14, fontFamily: 'Nunito Sans, sans-serif' }}>Setting</Typography>
          </div>
        }
        <List style={{ marginTop: !open ? -10 : null, marginLeft: !open ? -2 : null }}>
          {setting.map((item, index) => (
            <div style={{ marginTop: index === 0 ? null : 5 }} >
              {item.subItem.length !== 0 ?
                <a data-tip={item.label} data-for={item.label}>
                  <div style={{ justifyContent: 'space-between', flexDirection: 'row', display: 'flex', paddingLeft: 5, paddingRight: 10, cursor: 'pointer' }} onClick={() => { handleCollapseSetting(item) }}>
                    <ListItem key={item.label}>
                      <ListItemIcon style={{ minWidth: open ? 40 : 56 }}><img src={item.img} /></ListItemIcon>
                      <Typography style={{ fontFamily: 'Nunito Sans, sans-serif', color: '#525355', fontSize: 14 }}>{item.label}</Typography>
                    </ListItem>
                    {item.subItem.length !== 0 ? (item.collapse ? <ExpandLess style={{ color: "#525355", marginLeft: 50, alignSelf: 'center' }} /> : <ExpandMore style={{ color: "#525355", marginLeft: 50, alignSelf: 'center' }} />) : null}
                    {!open && (<ReactTooltip border={true} id={item.label} place="bottom" type="light" effect="solid" />)}
                  </div>
                </a>
                :
                <Link to={`${url}/${item.path}`}>
                  <div style={{ paddingLeft: 5 }} className={selectedIndex === item.label ? "active" : ""}>
                    <a data-tip={item.label} data-for={item.label}>
                      <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 Sans, sans-serif', color: '#525355', fontSize: 14 }}>{item.label}</Typography>
                      </ListItem>
                    </a>
                    {!open && (<ReactTooltip border={true} id={item.label} place="bottom" type="light" effect="solid" />)}
                  </div>
                </Link>
              }
              {item.subItem.length !== 0 &&
                <div>
                  <Collapse in={item.collapse} timeout="auto" unmountOnExit>
                    <List component="div" disablePadding>
                      {item.subItem.map((sub, indexs) => {
                        return (
                          <Link to={sub.label === "Logout" ? `/` : `${url}/${sub.path}`}>
                            <a data-tip={sub.label} data-for={sub.label}>
                              <div style={{ paddingLeft: 5, }} className={selectedSubIndex === sub.label ? "active" : ""} onClick={() => sub.label === "Logout" ? logout() : selectSub(sub.label)}>
                                <ListItem button style={{ paddingLeft: 57 }}>
                                  <Typography style={{ fontFamily: 'Nunito Sans, sans-serif', color: '#525355', fontSize: 14 }}>{sub.label}</Typography>
                                </ListItem>
                              </div>
                            </a>
                            {!open && (<ReactTooltip border={true} id={sub.label} place="bottom" type="light" effect="solid" />)}
                          </Link>
                        )
                      })}
                    </List>
                  </Collapse>
                </div>
              }
            </div>
          ))}
        </List>
        {open &&
          <div style={{ marginLeft: 20, marginTop: 5, paddingBottom: 20 }}>
            <button
              style={{
                outline: 'none',
                backgroundColor: 'transparent',
                cursor: 'pointer',
                borderColor: 'transparent',
              }}
              onClick={() => logout()}>
              <Typography style={{ color: '#525355', fontSize: 14, fontFamily: 'Nunito Sans, sans-serif' }}>Logout</Typography>
            </button>
          </div>
        }
      </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}
                  location={location}
                  children={<route.main height={height} width={width} open={open} location={location} selectIndex={selectIndex.bind(this)}/>}
                />
              ))}
            </Switch>
          </MuiPickersUtilsProvider>
          {/* <Footer>
            <Typography style={{ fontSize: '12px' }}>© EKSAD Technology. All rights reserved.</Typography>
          </Footer> */}
        </div>

      </div>
    </div>
  );
}