import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { usePipelineMappings } from "@qltr/queries";
import StoreContext from "@qltr/store";
import JobContext, { jobStatus } from "@qltr/jobs";
import { useJobIconState, usePipelineIconState } from "@qltr/util/JobTools";

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 ViewColumnIcon from "@mui/icons-material/ViewColumn";

import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import { asTree, asBranches, as1d } from "@qltr/util/pipelines.js";

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

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

  const navigate = useNavigate();
  const { data: pipelineMappings, isLoading } = usePipelineMappings();
  const { state: store } = useContext(StoreContext);

  const { jobFactory } = useContext(JobContext);

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

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

  const navigateToJob = () => {
    if (pipeline) return navigate(`/qualiteer/jobs#p${pipeline.id}`);
    navigate(`/qualiteer/jobs#${job.jobId}`);
  };

  const runTest = () => {
    if (isPipeline) return runPipelineTest();
    const jobId = jobFactory({ testNames: [testName], isTriage: true });
    if (store.focusJob) navigate(`/qualiteer/jobs#${jobId}`);
  };

  const runPipelineTest = () => {
    const primaries = pipelineMappings.filter((m) => m.includes(testName));
    const builderCache = {
      branches: asBranches(primaries),
      tree: asTree(primaries),
      selectedBranches: as1d(primaries),
      isTriage: true,
    };
    const pipeline = jobFactory(builderCache);
    if (store.focusJob) navigate(`/qualiteer/jobs#p${pipeline.id}`);
  };

  const jobOnClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (pipeline) return navigateToJob();
    if (!job) return runTest();
    navigateToJob();
  };

  function jobIcon() {
    if (pipeline) return usePipelineIconState(pipeline);
    if (!job) return <PlayArrowIcon />;
    return useJobIconState(job);
  }

  function Actions() {
    return (
      <React.Fragment>
        <IconButton
          color="success"
          aria-label="play"
          component="span"
          onClick={jobOnClick}
        >
          {jobIcon()}
        </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}
            {isPipeline && (
              <IconButton component="span">
                <ViewColumnIcon />
              </IconButton>
            )}
          </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" }}>
          {"Test info"}
        </Typography>
      </AccordionDetails>
    </Accordion>
  );
}
