import { BottomNavigation, BottomNavigationAction, Box, useTheme } from "@mui/material";
import {
  Dashboard as DevicesIcon,
  Home,
  MoreHoriz,
  Security,
  //SupervisedUserCircle,
  ShowChart as DemoIcon
} from "@mui/icons-material";
import { usePrevious } from "hooks";
import BindaptIcon from "products/Bindapt/BindaptIcon";
import BinsIcon from "products/Bindapt/BinsIcon";
import { useGlobalState } from "providers";
import { useCallback, useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { IsAdaptiveAgriculture, isBXT, IsMiVent, IsAdCon, IsOmniAir, IsMiPCA, IsIntellifarms } from "services/whiteLabel";
import FieldsIcon from "products/AgIcons/FieldsIcon";
import NexusSTIcon from "products/Construction/NexusSTIcon";
import OmniAirDeviceIcon from "products/AviationIcons/OmniAirDeviceIcon";
import AirportMapIcon from "products/AviationIcons/AirportMapIcon";
import PlaneIcon from "products/AviationIcons/PlaneIcon";
import JobsiteIcon from "products/Construction/JobSiteIcon";
import { useAuth0 } from "@auth0/auth0-react";

interface Props {
  sideIsOpen: boolean;
  setNavOpen: (value: React.SetStateAction<boolean>) => void
}

export default function BottomNavigator(props: Props) {
  const theme = useTheme();
  const { sideIsOpen, setNavOpen } = props;
  const navigate = useNavigate();
  const location = useLocation();
  const prevLocation = usePrevious(location);
  const { isAuthenticated } = useAuth0();
  const [{ user }] = useGlobalState();
  const [route, setRoute] = useState(sideIsOpen ? "side" : "");
  const isAg = IsAdaptiveAgriculture();
  const isIntel = IsIntellifarms();
  const isMiVent = IsMiVent();
  const isAdCon = IsAdCon();
  const isOmni = IsOmniAir();
  const isMiPCA = IsMiPCA();

  const reRoute = useCallback(
    (path: string) => {
      if (path === "") {
        if (isAg || isIntel) {
          return "bins";
        }
        if (isMiVent) {
          return "ventilation";
        }
        return "devices";
      }

      const deviceRoutes = ["groups", "devices", "demo"];
      if (deviceRoutes.find(r => path === r) !== undefined) {
        return "devices";
      }

      const moreRoutes = [
        "firmware",
        "users",
        "docs",
        "tutorial",
        "hardware",
        "data",
        "team",
        "sandbox"
      ];
      if (moreRoutes.find(r => path === r) !== undefined) {
        return "more";
      }
      return path;
    },
    [isAg, isMiVent, isIntel]
  );

  const autoDetectRoute = useCallback(() => {
    let path = location.pathname.split("/")[1];
    setRoute(reRoute(path));
  }, [location.pathname, reRoute]);

  useEffect(() => {
    if (!prevLocation || location !== prevLocation) {
      autoDetectRoute();
    }
  }, [location, prevLocation, autoDetectRoute]);

  const handleRouteChange = (newRoute: string) => {
    if (newRoute === "more") {
      setNavOpen(true);
    } else {
      navigate(`/${newRoute}`);
      setRoute(newRoute);
      setNavOpen(false)
    }
  };

  const getType = () => {
    return theme.palette.mode === "light" ? "dark" : "light"
  }

  const authenticatedNavigation = () => {
    return (
      <BottomNavigation value={route} onChange={(_, newValue) => handleRouteChange(newValue)}>
        {isAg || isIntel && (
          <BottomNavigationAction label="Farm" icon={<FieldsIcon type={getType()} />} value="visualFarm" />
        )}
        {isAg || isIntel && (
          <BottomNavigationAction label="Bins" icon={<BinsIcon type={getType()} />} value="bins" />
        )}
        {isAdCon && (
          <BottomNavigationAction
            label="Site Map"
            icon={<FieldsIcon type={getType()} />}
            value="constructionMap"
          />
        )}
        {(isOmni || isMiPCA) && (
          <BottomNavigationAction
            label="Map"
            icon={<AirportMapIcon type={getType()} />}
            value="aviationMap"
          />
        )}
        {(isOmni || isMiPCA) && (
          <BottomNavigationAction
            label="Terminals"
            icon={<PlaneIcon type={getType()} />}
            value="terminals"
          />
        )}

        <BottomNavigationAction
          label="Devices"
          icon={
            (isAg || isIntel) ? (
              <BindaptIcon type={getType()} />
            ) : isAdCon ? (
              <NexusSTIcon type={getType()} />
            ) : (isOmni || isMiPCA) ? (
              <OmniAirDeviceIcon type={getType()} />
            ) : (
              <DevicesIcon />
            )
          }
          value="devices"
        />
        {isAdCon && (
          <BottomNavigationAction
            label="Sites"
            icon={<JobsiteIcon type={getType()} />}
            value="jobsites"
          />
        )}
        {/* {isMiVent && (
          <BottomNavigationAction
            label="Ventilation"
            icon={<VentilationIcon type="light" />}
            value="ventilation"
          />
        )} */}

        {isBXT() && user.hasFeature("security") && (
          <BottomNavigationAction label="Security" icon={<Security />} value="security" />
        )}
        <BottomNavigationAction label="More" icon={<MoreHoriz />} value="more" />
      </BottomNavigation>
    );
  };

  // BXT specific navigation
  const unauthenticatedNavigation = () => {
    return (
      <BottomNavigation value={route} onChange={(_, newValue) => handleRouteChange(newValue)}>
        <BottomNavigationAction label="Demo" value="demo" icon={<DemoIcon />} />
        <BottomNavigationAction label="Home" icon={<Home />} value="" />
        <BottomNavigationAction label="More" icon={<MoreHoriz />} value="more" />
      </BottomNavigation>
    );
  };

  return (
    <Box
      position="fixed"
      bottom={0}
      width="100vw"
      zIndex={theme.zIndex.appBar}
      sx={{ background: theme.palette.background.paper }}
      style={{
        overflow:
          window.location.origin.includes("staging") || window.location.origin.includes("localhost")
            ? "scroll"
            : "visible"
      }}>
      {isAuthenticated ? authenticatedNavigation() : unauthenticatedNavigation()}
    </Box>
  );
}
