import React from "react";
import Button from "@mui/material/Button";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";

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

function PipelineTrackSelector(props) {
  const { cache, setCache, back, next } = props;
  const { primarySelectedMappings: primaries } = cache;
  const addTrack = (test) => {
    const tracks = cache.tracks ?? [];
    tracks.push(selectBranch(primaries, test));
    setCache({ ...cache, tracks });
  };

  const removeTrack = (test) => {
    const { tracks } = cache;
    for (var i in tracks) {
      const index = tracks[i].indexOf(test);
      if (index === -1) continue;
      tracks[i] = tracks[i].slice(0, index);
    }
    setCache({ ...cache, tracks });
  };

  const selectTrack = (test) => () => {
    if (as1d(cache.tracks).includes(test)) return removeTrack(test);
    addTrack(test);
  };

  const getColor = (test) =>
    as1d(cache.tracks).includes(test) ? "primary" : null;

  const nextClick = () => {
    setCache({
      ...cache,
      branches: asBranches(primaries),
      tree: asTree(cache.tracks),
      selectedBranches: as1d(cache.tracks),
    });
    next();
  };

  return (
    <React.Fragment>
      <DialogContent>
        <h3>Select Track</h3>
        {asBranches(primaries).map((track, i) => (
          <React.Fragment key={i}>
            <Typography variant="h6">{i + 1}</Typography>
            <Box>
              {track.map((test, j) => (
                <Accordion
                  expanded={false}
                  disableGutters={true}
                  square
                  key={j}
                  onClick={selectTrack(test)}
                >
                  <AccordionSummary
                    style={{
                      backgroundColor: "rgba(0, 0, 0, .03)",
                      flexWrap: "wrap",
                    }}
                  >
                    <Typography
                      component={"span"}
                      style={{ wordBreak: "break-word", margin: "auto 0" }}
                      color={getColor(test)}
                    >
                      {test}
                    </Typography>
                    <Stack sx={{ ml: "auto" }}>I</Stack>
                  </AccordionSummary>
                </Accordion>
              ))}
            </Box>
          </React.Fragment>
        ))}
      </DialogContent>
      <DialogActions>
        <Button onClick={back}>Back</Button>
        <Button onClick={nextClick} autoFocus>
          Next
        </Button>
      </DialogActions>
    </React.Fragment>
  );
}

export default PipelineTrackSelector;
