import { useEffect, useContext } from "react";
import StoreContext from "@qltr/store";
import JobContext from "@qltr/jobs";
import CatalogBox from "./CatalogBox.jsx";
import CatalogSearch from "./CatalogSearch.jsx";
import { useCatalogTests } from "@qltr/queries";
import TextField from "@mui/material/TextField";

export default function Catalog() {
  const { state: store, updateStore } = useContext(StoreContext);
  const { state: jobState } = useContext(JobContext);
  const { isLoading, data: tests } = useCatalogTests();
  const handleSearchChange = (e) =>
    updateStore({ catalogSearch: e.target.value });

  const handleSearchClear = () => updateStore({ catalogSearch: "" });

  useEffect(() => {
    return function unmount() {
      handleSearchClear();
    };
  }, []);

  const catalogWithJobs = () => {
    for (var test of tests) {
      if (test.isPipeline) {
        const pipeline = jobState.pipelines.find((p) =>
          p.selectedBranches.includes(test.name)
        );
        if (!pipeline) continue;
        const pipelineJob = jobState.jobs.find(
          (j) =>
            j.isPipeline &&
            j.pipelineId === pipeline.id &&
            j.branchId === test.name
        );
        if (!pipelineJob) test.pipeline = pipeline;
        test.job = pipelineJob;
        continue;
      }
      const job = jobState.jobs.find(
        (j) => !j.isPipeline && j.builderCache.testNames.includes(test.name)
      );
      if (job) test.job = job;
    }
    return tests;
  };

  return (
    <div className="catalog">
      <CatalogSearch
        onChange={handleSearchChange}
        onClear={handleSearchClear}
        clearOnUnmount
      />
      <h6>{store.catalogSearch}</h6>
      {isLoading
        ? null
        : catalogWithJobs().map((v, i) => (
            <CatalogBox key={i} catalogTest={v} />
          ))}
    </div>
  );
}
