import { ChevronRight, Code, Memory, People, Person, SyncAlt, TapAndPlay } from "@mui/icons-material";
import ChevronLeft from "@mui/icons-material/ChevronLeft";
import { 
  darken, 
  Divider, 
  Grid2 as Grid, 
  IconButton, 
  lighten, 
  List, 
  ListItemButton, 
  ListItemIcon, 
  ListItemText, 
  SwipeableDrawer, 
  Theme, 
  Toolbar, 
  Tooltip, 
  useTheme 
} from "@mui/material";
import classNames from "classnames";
import { useMobile, useWidth } from "../hooks/useWidth";
import { makeStyles } from "@mui/styles";
import BindaptIcon from "../products/Bindapt/BindaptIcon";
import { useLocation, useNavigate } from "react-router-dom";
import BinsIcon from "products/Bindapt/BinsIcon";
import { useGlobalState } from "providers";
import {
  IsAdaptiveAgriculture,
  // hasTutorialPlaylist,
  IsAdCon,
  // isBXT,
  IsMiVent,
  IsOmniAir,
  IsStreamline,
} from "services/whiteLabel";
import MiningIcon from "products/ventilation/MiningIcon";
import { useAuth0 } from "@auth0/auth0-react";
import FieldsIcon from "products/AgIcons/FieldsIcon";
import PlaneIcon from "products/AviationIcons/PlaneIcon";
import AirportMapIcon from "products/AviationIcons/AirportMapIcon";
import JobsiteIcon from "products/Construction/JobSiteIcon";
import { getThemeType } from "theme";
import ObjectHeaterIcon from "products/Construction/ObjectHeaterIcon";
import TasksIcon from "products/Construction/TasksIcon";
import CableIcon from "products/Bindapt/CableIcon";
import FieldListIcon from "products/AgIcons/FieldList";
import MarketplaceIcon from "products/CommonIcons/marketplaceIcon";
import DataDuckIcon from "products/Bindapt/DataDuckIcon";
import ContractsIcon from "products/CommonIcons/contractIcon";
import JohnDeereIcon from "products/CommonIcons/johnDeereIcon";
import CNHiIcon from "products/CommonIcons/cnhiIcon";
import LibraCartIcon from "products/CommonIcons/libracartIcon";

const drawerWidth = 230;

const useStyles = makeStyles((theme: Theme) => ({
  sideMenu: {
    position: "fixed",
    height: "100%",
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: "nowrap",
    background: theme.palette.background.default
  },
  sideMenuOpened: {
    zIndex: theme.zIndex.drawer + 2,
    width: drawerWidth,
    transition: theme.transitions.create(["width"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen
    })
  },
  sideMenuOnClosed: {
    transition: theme.transitions.create(["width"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    // overflowX: "hidden",
    width: theme.spacing(0),
    // zIndex: theme.zIndex.drawer,
    // opacity: 0,
    [theme.breakpoints.up("md")]: {
      width: theme.spacing(9.25),
      opacity: 1
    }
  },
  sideMenuOnClosedMobile: {
    transition: theme.transitions.create(["width"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    width: theme.spacing(0),
  },
  list: {
    paddingTop: 0
  },
  listItem: {
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(2),
    [theme.breakpoints.up("md")]: {
      paddingLeft: theme.spacing(3),
      paddingRight: theme.spacing(3)
    },
    "&:hover": {
      background: theme.palette.mode === "light" ? darken(theme.palette.background.default, 0.1) : lighten(theme.palette.background.default, 0.1)
    }
  }, 
  activeItem:
    theme.palette.mode === "light"
      ? {
          background: darken(theme.palette.background.default, 0.25),
          "&:hover": {
            background: darken(theme.palette.background.default, 0.15)
          }
        }
      : {
          background: lighten(theme.palette.background.default, 0.25),
          "&:hover": {
            background: lighten(theme.palette.background.default, 0.15)
          }
        }
}))

interface Props {
  open: boolean;
  onOpen: () => void;
  onClose: () => void;
}
  
export default function SideNavigator(props: Props) {
  const { open, onOpen, onClose } = props;
  const { isAuthenticated } = useAuth0()
  const theme = useTheme();
  const width = useWidth();
  const classes = useStyles();
  const location = useLocation();
  const [{ user }] = useGlobalState()
  const isMobile = useMobile();

  const navigate = useNavigate();

  const getClasses = (page: string) => {
    if (page === "/device") {
      if (location.pathname.startsWith("/device") ||
      location.pathname.startsWith("/group")) {
        return ({
          root: `${classes.listItem} ${classes.activeItem}`
        })
      }
    }
    if (location.pathname.startsWith(page)) {
      return ({
        root: `${classes.listItem} ${classes.activeItem}`
      })
    }
    return ({
      root: `${classes.listItem}`
    })
  }

  const goTo = (url: string) => {
    onClose();
    navigate(url)
  }

  const authenticatedSideMenu = () => {
    const isMiVent = IsMiVent();
    const isAg = IsAdaptiveAgriculture()
    const isStreamline = IsStreamline()
    const isMiPCA = IsOmniAir()
    const isAdCon = IsAdCon()
    return (
      <List className={classes.list} component="nav">
        {(isAg || isStreamline || user.hasFeature("admin")) && (
        <Tooltip title="Visual Farm" placement="right">
          <ListItemButton
            id="tour-visual-farm"
            onClick={() => goTo("/visualFarm")}
            classes={getClasses("/visualFarm")}
            >
            <ListItemIcon>
              <FieldsIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Visual Farm" />}
          </ListItemButton>
        </Tooltip>
        )}
        {(isMiPCA || user.hasFeature("admin")) && (
        <Tooltip title="Aviation Map" placement="right">
          <ListItemButton
            id="tour-aviation-map"
            onClick={() => goTo("/aviationMap")}
            classes={getClasses("/aviationMap")}
            >
            <ListItemIcon>
              <AirportMapIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Airport Map" />}
          </ListItemButton>
        </Tooltip>
        )}
        {(isAdCon || user.hasFeature("admin")) && (
        <Tooltip title="Construction Map" placement="right">
          <ListItemButton
            id="tour-construction-map"
            onClick={() => goTo("/constructionMap")}
            classes={getClasses("/constructionMap")}
            >
            <ListItemIcon>
              <FieldsIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Construction Map" />}
          </ListItemButton>
        </Tooltip>
        )}
        {(isAg || isStreamline || user.hasFeature("admin")) && (
          <Tooltip title="Contracts" placement="right">
            <ListItemButton
              id="tour-contracts"
              onClick={() => goTo("/contracts")}
              classes={getClasses("/contracts")}
              >
              <ListItemIcon>
                <ContractsIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Contracts" />}
            </ListItemButton>
          </Tooltip>
        )}
        {(isAg || isStreamline || user.hasFeature("admin")) && (
        <Tooltip title="Bins" placement="right">
          <ListItemButton
            id="tour-bins"
            onClick={() => goTo("/bins")}
            classes={getClasses("/bin")}
            >
            <ListItemIcon>
              <BinsIcon height={"26px"}/>
            </ListItemIcon>
            {open && <ListItemText primary="Bins" />}
          </ListItemButton>
        </Tooltip>
        )}
        {(isMiPCA || user.hasFeature("admin")) && (
          <Tooltip title="Terminals" placement="right">
            <ListItemButton
              id="tour-terminals"
              onClick={() => goTo("/terminals")}
              classes={getClasses("/terminal")}
              >
              <ListItemIcon>
                <PlaneIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Terminals" />}
            </ListItemButton>
          </Tooltip>
        )}
        {(user.hasFeature("installer") && isAg || user.hasFeature("admin")) &&
          <Tooltip title="Cable Estimator" placement="right">
            <ListItemButton
              id="tour-cable-estimator"
              onClick={() => goTo("/cableEstimate")}
              classes={getClasses("/cableEstimate")}
              >
              <ListItemIcon>
                <CableIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Cable Estimator" />}
            </ListItemButton>
          </Tooltip>
        }
        {(isAg || isStreamline || user.hasFeature("admin")) && (
          <Tooltip title="Transactions" placement="right">
            <ListItemButton
              id="tour-transactions"
              onClick={() => goTo("/transactions")}
              classes={getClasses("/transactions")}
              >
              <ListItemIcon>
                <SyncAlt />
              </ListItemIcon>
              {open && <ListItemText primary="Transactions" />}
            </ListItemButton>
          </Tooltip>
        )}
        {(isMiVent || user.hasFeature("admin")) && (
          <Tooltip title="Mines" placement="right">
            <ListItemButton
              id="tour-mines"
              onClick={() => goTo("/mines")}
              classes={getClasses("/mine")}
              >
              <ListItemIcon>
                <MiningIcon height={"26px"} width={"26px"} />
              </ListItemIcon>
              {open && <ListItemText primary="Mines" />}
            </ListItemButton>
          </Tooltip>
        )}
        <Tooltip title="Devices" placement="right">
          <ListItemButton
            id="tour-dashboard"
            onClick={() => goTo("/devices")}
            classes={getClasses("/device")}
            >
            <ListItemIcon>
              <BindaptIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Devices" />}
          </ListItemButton>
        </Tooltip>
        {user.hasFeature("admin") &&
          <Tooltip title="Firmware" placement="right">
            <ListItemButton
              id="tour-firmware"
              onClick={() => goTo("/firmware")}
              classes={getClasses("/firmware")}
              >
              <ListItemIcon>
                <Memory />
              </ListItemIcon>
              {open && <ListItemText primary="Logs" />}
            </ListItemButton>
          </Tooltip>
        }
        {user.hasFeature("admin") &&
          <Tooltip title="Logs" placement="right">
            <ListItemButton
              id="tour-logs"
              onClick={() => goTo("/logs")}
              classes={getClasses("/logs")}
              >
              <ListItemIcon>
                <DataDuckIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Logs" />}
            </ListItemButton>
          </Tooltip>
        }
        <Tooltip title="Teams" placement="right">
          <ListItemButton
            id="tour-teams"
            onClick={() => goTo("/teams")}
            classes={getClasses("/team")} 
            >
            <ListItemIcon>
              <People style={{ color: getThemeType() === "light" ? "black" : undefined }}/>
            </ListItemIcon>
            {open && <ListItemText primary="Teams" />}
          </ListItemButton>
        </Tooltip>
        <Tooltip title="Users" placement="right">
          <ListItemButton
            id="tour-users"
            onClick={() => goTo("/users")}
            classes={getClasses("/user")}
          >
            <ListItemIcon>
              <Person style={{ color: getThemeType() === "light" ? "black" : undefined }}/>
            </ListItemIcon>
            {open && <ListItemText primary="Users" />}
          </ListItemButton>
        </Tooltip>
        {(isAg || isStreamline || user.hasFeature("admin")) && (
        <Tooltip title="My Fields" placement="right">
          <ListItemButton
            id="tour-field-list"
            onClick={() => goTo("/fields")}
            classes={getClasses("/fields")}
            >
            <ListItemIcon>
              <FieldListIcon />
            </ListItemIcon>
            {open && <ListItemText primary="My Fields" />}
          </ListItemButton>
        </Tooltip>
        )}

        {(isAdCon || user.hasFeature("admin")) && (
        <Tooltip title="Jobsites" placement="right">
          <ListItemButton
            id="tour-jobsites"
            onClick={() => goTo("/jobsites")}
            classes={getClasses("/jobsites")}
            >
            <ListItemIcon>
              <JobsiteIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Jobsites" />}
          </ListItemButton>
        </Tooltip>
        )}
        {(isAdCon || user.hasFeature("admin")) && (
        <Tooltip title="Heaters" placement="right">
          <ListItemButton
            id="tour-heaters"
            onClick={() => goTo("/heaters")}
            classes={getClasses("/heaters")}
            >
            <ListItemIcon>
              <ObjectHeaterIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Heaters" />}
          </ListItemButton>
        </Tooltip>
        )}
        <Tooltip title="Tasks" placement="right">
          <ListItemButton
            id="tour-tasks"
            onClick={() => goTo("/tasks")}
            classes={getClasses("/tasks")}
            >
            <ListItemIcon>
              <TasksIcon />
            </ListItemIcon>
            {open && <ListItemText primary="Tasks" />}
          </ListItemButton>
        </Tooltip>

        {user.hasFeature("developer") &&
          <Tooltip title="API documentation" placement="right">
            <ListItemButton
              id="tour-api-docs"
              onClick={() => goTo("/api")}
              classes={getClasses("/api")}
              >
              <ListItemIcon>
                <Code />
              </ListItemIcon>
              {open && <ListItemText primary="API Documentation" />}
            </ListItemButton>
          </Tooltip>
        }
        {user.hasFeature("admin") && window.NDEFReader &&
          <Tooltip title="NFC" placement="right">
            <ListItemButton
              id="tour-nfc"
              onClick={() => goTo("/nfc")}
              classes={getClasses("/nfc")}
              >
              <ListItemIcon>
                <TapAndPlay />
              </ListItemIcon>
              {open && <ListItemText primary="NFC" />}
            </ListItemButton>
          </Tooltip>
        }
        {(isAg || isStreamline || user.hasFeature("admin")) &&
          <Tooltip title="Marketplace" placement="right">
            <ListItemButton
              id="tour-marketplace"
              onClick={() => goTo("/marketplace")}
              classes={getClasses("/marketplace")}
              >
              <ListItemIcon>
                <MarketplaceIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Marketplace" />}
            </ListItemButton>
          </Tooltip>
        }
        {user.hasFeature("john-deere") &&
          <Tooltip title="John Deere" placement="right">
            <ListItemButton
              id="tour-jd"
              onClick={() => goTo("/johndeere")}
              classes={getClasses("/johndeere")}
              >
              <ListItemIcon>
                <JohnDeereIcon />
              </ListItemIcon>
              {open && <ListItemText primary="John Deere" />}
            </ListItemButton>
          </Tooltip>
        }
        {user.hasFeature("cnhi") &&
          <Tooltip title="Case New Holland" placement="right">
            <ListItemButton
              id="tour-cnhi"
              onClick={() => goTo("/cnhi")}
              classes={getClasses("/cnhi")}
              >
              <ListItemIcon>
                <CNHiIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Case New Holland" />}
            </ListItemButton>
          </Tooltip>
        }
        {user.hasFeature("libra-cart") &&
          <Tooltip title="Libra Cart" placement="right">
            <ListItemButton
              id="tour-libraCart"
              onClick={() => goTo("/libracart")}
              classes={getClasses("/libracart")}
              >
              <ListItemIcon>
                <LibraCartIcon />
              </ListItemIcon>
              {open && <ListItemText primary="Libra Cart" />}
            </ListItemButton>
          </Tooltip>
        } 
      </List>
    )
  }

  return (
    <SwipeableDrawer
      // variant={width === "xs" || width === "sm" ? "temporary" : "permanent"}
      variant={!open ? "permanent" : width === "xs" || width === "sm" ? "temporary" : "permanent"}
      classes={{
        paper: classNames(
          classes.sideMenu,
          open ? classes.sideMenuOpened : (isMobile ? classes.sideMenuOnClosedMobile : classes.sideMenuOnClosed)
        )
      }}
      anchor="left"
      open={open}
      onOpen={onOpen}
      onClose={onClose}
      sx={{ pointerEvents: isMobile&&!open ? "none" : "auto"}}
    >
      <Toolbar >
        <Grid container direction="row" justifyContent={"flex-end"}>
          <Grid>
            <IconButton onClick={onClose} aria-label="onClose side menu">
              {theme.direction === "rtl" ? <ChevronRight /> : <ChevronLeft />}
            </IconButton>
          </Grid>
        </Grid>
      </Toolbar>
      <Divider />
      {/* {isAuthenticated || isOffline() ? authenticatedSideMenu() : unauthenticatedSideMenu()} */}
      {isAuthenticated && authenticatedSideMenu()}
    </SwipeableDrawer>
  );
}