import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import StoreContext from "../../ctx/StoreContext.jsx";
import JobContext from "../../ctx/JobContext.jsx";

import Accordion from "@mui/material/Accordion";
import AccordionDetails from "@mui/material/AccordionDetails";
import AccordionSummary from "@mui/material/AccordionSummary";
import Typography from "@mui/material/Typography";

import IconButton from "@mui/material/IconButton";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";

import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";

export default function CatalogBox(props) {
  const { catalogTest } = props;

  const {
    name: testName,
    class: testClass,
    repo: testRepo,
    isCompound,
    type: testType,
  } = catalogTest;

  const navigate = useNavigate();

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

  const { state: jobState, jobBuilder } = useContext(JobContext);

  const [open, setOpen] = useState(false);

  const toggleOpen = () => setOpen(!open);

  const runTest = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const jobId = jobBuilder([catalogTest]);
    if (store.focusJob) navigate(`/qualiteer/jobs#${jobId}`);
  };

  function Actions() {
    return (
      <React.Fragment>
        <IconButton
          color="success"
          aria-label="play"
          component="span"
          onClick={runTest}
        >
          <PlayArrowIcon />
        </IconButton>
      </React.Fragment>
    );
  }

  return (
    <Accordion
      expanded={open}
      disableGutters={true}
      onChange={toggleOpen}
      square
    >
      <AccordionSummary
        style={{
          backgroundColor: "rgba(0, 0, 0, .03)",
          flexWrap: "wrap",
        }}
      >
        <Typography
          component={"span"}
          style={{ wordBreak: "break-word", margin: "auto 0" }}
        >
          {`${testClass}#`}
          <Box fontWeight="bold" display="inline">
            {testName}
          </Box>
          <br />
        </Typography>

        <Stack
          sx={{ ml: "auto", display: { md: "none", lg: "none", xl: "none" } }}
        >
          <Actions />
        </Stack>
        <Stack
          direction="row"
          sx={{
            ml: "auto",
            display: { xs: "none", sm: "none", md: "flex", lg: "flex" },
          }}
        >
          <Actions />
        </Stack>
      </AccordionSummary>
      <AccordionDetails>
        <Typography component={"span"} style={{ wordBreak: "break-word" }}>
          {JSON.stringify(catalogTest)}
        </Typography>
      </AccordionDetails>
    </Accordion>
  );
}
