import { useState, useContext } from "react";
import StoreContext from "../../ctx/StoreContext.jsx";
import JobContext from "../../ctx/JobContext.jsx";
import SilenceDialog from "../alerting/SilenceDialog.jsx";
import FailingBox from "./FailingBox.jsx";

import SpeedDial from "@mui/material/SpeedDial";
import SpeedDialAction from "@mui/material/SpeedDialAction";
import SpeedDialIcon from "@mui/material/SpeedDialIcon";

import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";

import ReplayIcon from "@mui/icons-material/Replay";

export default function Failing() {
  const { state: jobState, retryAll, activeJobStates } = useContext(JobContext);

  const {
    state: store,
    updateStore,
    silenceRequest,
  } = useContext(StoreContext);
  const { failing } = store;

  const [silenceEntry, setSilenceEntry] = useState({ open: false });

  const closeSilence = () => setSilenceEntry({ ...silenceEntry, open: false });

  const handleSilenceClose = (silenceReq) => {
    closeSilence();
    if (!silenceReq) return;
    silenceRequest(silenceReq);
  };

  const editSilence = (silence) => () => {
    setSilenceEntry({ ...silence, open: true });
  };

  const [retryAllOpen, setRetryAllOpen] = useState(false);
  const retryAllClick = () => setRetryAllOpen(!retryAllOpen);

  const handleClose = (confirmed) => () => {
    retryAllClick();
    if (!confirmed) return;
    retryAll(store.failing);
  };

  return (
    <div className="failing">
      {failing.map((v, i) => (
        <FailingBox key={i} failingTest={v} silenceClick={editSilence(v)} />
      ))}

      <Dialog
        open={retryAllOpen}
        onClose={handleClose()}
        sx={{ "& .MuiDialog-paper": { width: "80%", maxHeight: 435 } }}
        maxWidth="xs"
      >
        <DialogTitle>Retry all failing tests?</DialogTitle>
        <DialogContent>
          <DialogContentText>
            This will create x jobs and run y tests
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose()}>Cancel</Button>
          <Button onClick={handleClose(true)} autoFocus>
            Yes
          </Button>
        </DialogActions>
      </Dialog>
      <SilenceDialog
        keepMounted
        open={silenceEntry.open}
        onClose={handleSilenceClose}
        silence={silenceEntry}
      />
      <SpeedDial
        ariaLabel="Retry All"
        sx={{ position: "fixed", bottom: 16, right: 16 }}
        icon={<ReplayIcon />}
        onClick={retryAllClick}
        open={false}
      />
    </div>
  );
}
