import { useContext, useState } from "react";
import { useCurrentlyFailing } from "@qltr/queries";
import JobContext from "@qltr/jobs";
import StoreContext from "@qltr/store";

import { Link, useLocation } from "react-router-dom";
import AppBar from "@mui/material/AppBar";
import Badge from "@mui/material/Badge";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import MenuIcon from "@mui/icons-material/Menu";
import Avatar from "@mui/material/Avatar";
import Drawer from "@mui/material/Drawer";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import List from "@mui/material/List";
import ListItemButton from "@mui/material/ListItemButton";
import NotificationsIcon from "@mui/icons-material/Notifications";
import WorkIcon from "@mui/icons-material/Work";
import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted";
import SettingsIcon from "@mui/icons-material/Settings";
import WarningIcon from "@mui/icons-material/Warning";
import InfoIcon from "@mui/icons-material/Info";
import SentimentSatisfiedAltIcon from "@mui/icons-material/SentimentSatisfiedAlt";

const drawerWidth = 250;

export default function Navbar() {
  const { state: jobState } = useContext(JobContext);
  const { state: store } = useContext(StoreContext);
  const { isLoading, data: failing } = useCurrentlyFailing();
  const pages = store.pages;
  const icons = [
    <Badge badgeContent={(failing ?? []).length} color="error">
      {(failing ?? []).length > 0 ? (
        <WarningIcon />
      ) : (
        <SentimentSatisfiedAltIcon />
      )}
    </Badge>,
    <NotificationsIcon />,
    <Badge
      badgeContent={
        jobState.jobs.filter((j) => !j.isPipeline).length +
        jobState.pipelines.length
      }
      color="primary"
    >
      <WorkIcon />
    </Badge>,
    <FormatListBulletedIcon />,
    <SettingsIcon />,
    <InfoIcon />,
  ];

  const location = useLocation();
  const [drawerOpen, setDrawer] = useState(false);

  const toggleDrawer = () => setDrawer(!drawerOpen);
  const closeDrawer = () => setDrawer(false);

  const reloadPage = () => window.location.reload(false);

  const SideBadge = styled(Badge)(({ theme }) => ({
    "& .MuiBadge-badge": {
      right: -6,
      top: 10,
      padding: "0 4px",
    },
  }));

  const navHeader = () => {
    const name = location.pathname.split("/").pop();

    const pathStr = name.charAt(0).toUpperCase() + name.slice(1);
    if (location.pathname !== "/qualiteer/failing") return pathStr;
    return (
      <SideBadge
        badgeContent={(failing ?? []).length}
        color="error"
        overlap="circular"
      >
        {pathStr}
      </SideBadge>
    );
  };

  const drawerIndex = (isDrawer) => (theme) =>
    theme.zIndex.modal + 2 - (isDrawer ? 1 : 0);

  return (
    <AppBar position="fixed" sx={{ bgcolor: "black", zIndex: drawerIndex() }}>
      <Box sx={{ flexGrow: 1, margin: "0 20px" }}>
        <Toolbar disableGutters>
          <IconButton
            size="large"
            edge="start"
            color="inherit"
            aria-label="menu"
            sx={{ mr: 2 }}
            onClick={toggleDrawer}
          >
            <MenuIcon />
          </IconButton>
          <Drawer
            open={drawerOpen}
            onClose={closeDrawer}
            sx={{ zIndex: drawerIndex(true) }}
          >
            <Toolbar />
            <Box
              sx={{ width: drawerWidth, overflow: "auto" }}
              role="presentation"
            >
              <List>
                {pages.map((text, index) => (
                  <ListItemButton
                    key={text}
                    component={Link}
                    to={"/qualiteer/" + text}
                    selected={location.pathname === "/qualiteer/" + text}
                    onClick={closeDrawer}
                  >
                    <ListItemIcon>{icons[index]}</ListItemIcon>
                    <ListItemText
                      primary={text.charAt(0).toUpperCase() + text.slice(1)}
                    />
                  </ListItemButton>
                ))}
              </List>
            </Box>
          </Drawer>
          <Typography variant="h6" noWrap component="div" sx={{ flexGrow: 1 }}>
            {navHeader()}
          </Typography>
          <Avatar
            style={{ cursor: "pointer" }}
            alt="QA"
            src="/qualiteer/assets/QA.png"
            onClick={reloadPage}
          />
        </Toolbar>
      </Box>
    </AppBar>
  );
}
