import React, { useState, useContext, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";

import JobContext from "../../ctx/JobContext.jsx";
import JobBox from "./JobBox.jsx";
import JobView from "./JobView.jsx";
import JobBuilder from "./builder/JobBuilder.jsx";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";

export default function Jobs() {
  const { state: jobState } = useContext(JobContext);
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const jobName = location.hash.slice(1);
    if (!jobName || jobState.jobs.find((job) => job.name === jobName)) return;
    navigate("/qualiteer/jobs");
  });

  return (
    <div className="jobs">
      {jobState.jobs.length === 0 ? (
        <React.Fragment>
          <Box
            display="flex"
            alignItems="center"
            justifyContent="center"
            sx={{ flexFlow: "wrap" }}
          >
            <Typography variant="h4">No jobs found! </Typography>{" "}
          </Box>
          <Box
            display="flex"
            alignItems="center"
            justifyContent="center"
            sx={{ flexFlow: "wrap" }}
          >
            {" "}
            <Typography variant="h5">
              Click the '+' to start a new one!
            </Typography>
          </Box>
        </React.Fragment>
      ) : null}
      <JobBuilder />
      {location.hash === "" &&
        jobState.jobs
          .filter((j) => !j.isPipeline)
          .map((v, i) => (
            <a
              key={i}
              href={`/qualiteer/jobs#${v.name}`}
              style={{ textDecoration: "none" }}
            >
              <JobBox job={v} />
            </a>
          ))}
      {jobState.jobs.find((job) => job.name === location.hash.slice(1)) && (
        <JobView
          job={jobState.jobs.find((job) => job.name === location.hash.slice(1))}
        />
      )}
    </div>
  );
}
