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

import JobContext from "@qltr/jobs";
import JobBox from "./JobBox.jsx";
import JobPipelineBox from "./JobPipelineBox.jsx";
import JobView from "./JobView.jsx";
import JobPipelineDisplay from "./JobPipelineDisplay.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);
    const pipelineId = jobName.slice(1);
    if (!jobName || !pipelineId) return;
    const hasJob = jobState.pipelines.find((p) => p.id === pipelineId);
    const hasPipeline = jobState.jobs.find((job) => job.name === jobName);
    if (hasPipeline || hasJob) return;
    if (jobName || pipelineId) 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 === "" && (
        <React.Fragment>
          {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.pipelines.map((p, i) => (
            <a
              key={i}
              style={{ textDecoration: "none" }}
              href={`/qualiteer/jobs#p${p.id}`}
            >
              <JobPipelineBox pipeline={p} />
            </a>
          ))}
        </React.Fragment>
      )}

      {location.hash[1] === "p"
        ? jobState.pipelines.find((p) => p.id === location.hash.slice(2)) && (
            <JobPipelineDisplay
              pipeline={jobState.pipelines.find(
                (p) => p.id === location.hash.slice(2)
              )}
            />
          )
        : jobState.jobs.find((job) => job.name === location.hash.slice(1)) && (
            <JobView
              job={jobState.jobs.find(
                (job) => job.name === location.hash.slice(1)
              )}
            />
          )}
    </div>
  );
}
