import React, { useContext, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import JobContext, { jobStatus } from "@qltr/jobs";
import StoreContext from "@qltr/store";
import Box from "@mui/material/Box";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";

import JobLogView from "./JobLogView.jsx";
import ListItemText from "@mui/material/ListItemText";
import ListItemIcon from "@mui/material/ListItemIcon";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import DownloadIcon from "@mui/icons-material/Download";
import ReplayIcon from "@mui/icons-material/Replay";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import DoNotDisturbIcon from "@mui/icons-material/DoNotDisturb";
import DeleteIcon from "@mui/icons-material/Delete";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";

export default function JobView(props) {
  const navigate = useNavigate();
  const { job } = props;
  const { jobFactory, jobCancel, jobDestroy } = useContext(JobContext);
  const { state: store } = useContext(StoreContext);
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  function download(filename, text) {
    var element = document.createElement("a");
    element.setAttribute(
      "href",
      "data:text/plain;charset=utf-8," + encodeURIComponent(text)
    );
    element.setAttribute("download", filename);
    element.style.display = "none";
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }

  function retryJob() {
    const jobId = jobFactory(job.builderCache);
    if (store.focusJob) navigate(`/qualiteer/jobs#${jobId}`);
  }

  function downloadLog() {
    if (job.status === jobStatus.PENDING) return;
    download(`${job.jobId}.txt`, job.log.join("\n"));
  }

  function cancelJob() {
    jobCancel(job.jobId);
  }

  function deleteJob() {
    jobDestroy(job.jobId);
    navigateToJobs();
  }

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

  function navigateToJobs() {
    if (job.isPipeline) return navigate(`/qualiteer/jobs#p${job.pipelineId}`);
    navigate("/qualiteer/jobs");
  }

  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" }}>
              {job.name}
            </Typography>
            <IconButton onClick={handleClick}>
              <MoreVertIcon />
            </IconButton>
          </Toolbar>
        </Box>
      </AppBar>
      <Toolbar disableGutters />
      <JobLogView log={job.log} status={job.status} />
      <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
        <MenuItem onClick={menuSelect(downloadLog)}>
          <ListItemIcon>
            <DownloadIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Download Log</ListItemText>
        </MenuItem>
        {!job.isPipeline && (
          <MenuItem onClick={menuSelect(retryJob)}>
            <ListItemIcon>
              {job.status === jobStatus.OK || job.status === jobStatus.ERROR ? (
                <ReplayIcon fontSize="small" />
              ) : (
                <PlayArrowIcon fontSize="small" />
              )}
            </ListItemIcon>
            <ListItemText>
              {job.status === jobStatus.ERROR ? "Retry" : "Duplicate"}
            </ListItemText>
          </MenuItem>
        )}
        {job.status === jobStatus.OK ||
        job.status === jobStatus.ERROR ||
        job.status === jobStatus.CANCELED ? null : (
          <MenuItem onClick={menuSelect(cancelJob)}>
            <ListItemIcon>
              <DoNotDisturbIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>Cancel</ListItemText>
          </MenuItem>
        )}
        {!job.isPipeline && (
          <MenuItem onClick={menuSelect(deleteJob)}>
            <ListItemIcon>
              <DeleteIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>Delete</ListItemText>
          </MenuItem>
        )}
      </Menu>
    </Box>
  );
}
