import { useState, useContext } from "react";
import StoreContext from "../../ctx/StoreContext.jsx";
import SilencedBox from "./SilencedBox.jsx";
import SilenceDialog from "./SilenceDialog.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";

export default function Alerting() {
  const {
    state: store,
    updateStore,
    silenceRequest,
  } = useContext(StoreContext);

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

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

  const handleDeleteClose = (makeRequest) => () => {
    const silenceReq = { ...silenceEntry };
    closeSilence();
    if (!makeRequest) return;
    silenceRequest({ ...silenceReq, silencedUntil: null });
  };

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

  const quickAlertClick = () => {
    setSilenceEntry({ open: true, deleteOpen: false });
  };

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

  const removeSilence = (silence) => () => {
    setSilenceEntry({ ...silence, deleteOpen: true, open: false });
  };

  return (
    <div className="alerting">
      {store.silenced.map((v, i) => (
        <SilencedBox
          key={i}
          silenceEntry={v}
          editSilence={editSilence(v)}
          removeSilence={removeSilence(v)}
        />
      ))}
      <Dialog
        open={silenceEntry.deleteOpen}
        onClose={handleDeleteClose()}
        sx={{ "& .MuiDialog-paper": { width: "80%", maxHeight: 435 } }}
        maxWidth="xs"
      >
        <DialogTitle>Resume Alerting</DialogTitle>
        <DialogContent>Are you sure you want to resume alerting?</DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteClose()}>Cancel</Button>
          <Button onClick={handleDeleteClose(true)} autoFocus>
            Remove
          </Button>
        </DialogActions>
      </Dialog>

      <SilenceDialog
        keepMounted
        open={silenceEntry.open}
        onClose={handleClose}
        silence={silenceEntry}
      />

      <SpeedDial
        ariaLabel="Silence Alert"
        sx={{ position: "fixed", bottom: 16, right: 16 }}
        icon={<SpeedDialIcon />}
        onClick={quickAlertClick}
        open={false}
      />
    </div>
  );
}
