import React, { useContext } from "react";
import { useNavigate } from "react-router-dom";
import JobContext, { jobStatus } from "@qltr/jobs";
import {
  selectedPipelineBranches,
  pipelineJobs,
  findPipelineJobByTestName,
  useJobIconState,
} from "@qltr/util/JobTools";

import Box from "@mui/material/Box";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";

import Accordion from "@mui/material/Accordion";
import AccordionSummary from "@mui/material/AccordionSummary";
import Stack from "@mui/material/Stack";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import IconButton from "@mui/material/IconButton";
import CheckIcon from "@mui/icons-material/Check";
import ClearIcon from "@mui/icons-material/Clear";
import ViewColumnIcon from "@mui/icons-material/ViewColumn";
import PendingIcon from "@mui/icons-material/Pending";
import VisibilityIcon from "@mui/icons-material/Visibility";
import DoNotDisturbIcon from "@mui/icons-material/DoNotDisturb";

import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import ListItemText from "@mui/material/ListItemText";
import ListItemIcon from "@mui/material/ListItemIcon";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import DeleteIcon from "@mui/icons-material/Delete";

function JobPipelineDisplay(props) {
  const { pipeline } = props;
  const {
    state: jobState,
    pipelineCancel,
    pipelineDestroy,
  } = useContext(JobContext);
  const navigate = useNavigate();

  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  const selectJob = (testName) => () => {
    const job = findPipelineJobByTestName(pipeline, jobState.jobs, testName);
    if (!job) return;
    navigate(`/qualiteer/jobs#${job.jobId}`);
  };

  function navigateToJobs() {
    navigate(`/qualiteer/jobs`);
  }

  function cancelPipeline() {
    pipelineCancel(pipeline.id);
  }

  function deletePipeline() {
    pipelineDestroy(pipeline.id);
  }

  const menuSelect = (cb) => () => {
    handleClose();
    cb();
  };

  function pipelineActive() {
    return pipelineJobs(pipeline, jobState.jobs).find(
      (j) => j.status === jobStatus.ACTIVE || j.status === jobStatus.PENDING
    );
  }

  function jobIcon(name) {
    if (pipeline.isCanceled) return <DoNotDisturbIcon color="warning" />;
    const job = findPipelineJobByTestName(pipeline, jobState.jobs, name);
    if (!job) return <ViewColumnIcon color="secondary" />;
    return useJobIconState(job);
  }

  return (
    <Box>
      <AppBar
        position="fixed"
        sx={{
          backgroundColor: "white",
          boxShadow: "none",
          color: "black",
        }}
      >
        <Toolbar disableGutters />
        <Box sx={{ flexGrow: 1, margin: "0 10px" }}>
          <Toolbar disableGutters>
            <IconButton onClick={navigateToJobs}>
              <ArrowBackIcon />
            </IconButton>
            <Typography variant="h6" sx={{ ml: "auto", mr: "auto" }}>
              {pipeline.id}
            </Typography>
            <IconButton onClick={handleClick}>
              <MoreVertIcon />
            </IconButton>
          </Toolbar>
        </Box>
      </AppBar>
      <Toolbar disableGutters />
      {selectedPipelineBranches(pipeline).map((track, i) => (
        <React.Fragment key={i}>
          <Typography variant="h6">{i + 1}</Typography>
          <Box>
            {track.map((test, j) => (
              <Accordion
                expanded={false}
                disableGutters={true}
                square
                key={j}
                onClick={selectJob(test)}
              >
                <AccordionSummary
                  style={{
                    backgroundColor: "rgba(0, 0, 0, .03)",
                    flexWrap: "wrap",
                  }}
                >
                  <Typography
                    component={"span"}
                    style={{ wordBreak: "break-word", margin: "auto 0" }}
                  >
                    {test}
                  </Typography>
                  <Stack sx={{ ml: "auto" }}>
                    <IconButton aria-label="retry" component="span">
                      {jobIcon(test)}
                    </IconButton>
                  </Stack>
                </AccordionSummary>
              </Accordion>
            ))}
          </Box>
        </React.Fragment>
      ))}

      <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
        {pipelineActive() ? (
          <MenuItem onClick={menuSelect(cancelPipeline)}>
            <ListItemIcon>
              <DoNotDisturbIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>Cancel</ListItemText>
          </MenuItem>
        ) : null}
        <MenuItem onClick={menuSelect(deletePipeline)}>
          <ListItemIcon>
            <DeleteIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Delete</ListItemText>
        </MenuItem>
      </Menu>
    </Box>
  );
}

export default JobPipelineDisplay;
