import React, { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import ActiveJobs from "../components/MyActiveJobs/ActiveJobs";
import usersService from "../services/UsersService";

/**
 * This code defines a React functional component called `ManageActiveJobs`.
 * It fetches a list of active job messages and renders the `ActiveJobs` component with the necessary props.
 */
function ManageActiveJobs() {
  const ApiCall = new usersService();

  const navigate = useNavigate();
  const { state } = useLocation();

  const [details, setDetails] = useState({});

  const [activeJobMesList, setActiveJobMesList] = useState({
    loading: true,
    error: false,
    data: [],
  });

  const [activeJobMesListReload, setActiveJobMesListReload] = useState(false);

  /**
   * Fetches the active job message list.
   */
  const getActiveJobMesList = () => {
    setActiveJobMesList({ loading: true, error: false, data: [] });
    const contract = { contract: state.contract };
    ApiCall.activeJobMesList(contract)
      .then((res) => {
        if (res.status !== 200 || res.data.internal_return < 0) {
          setActiveJobMesList({ loading: false, error: false, data: [] });
          return;
        }
        setActiveJobMesList({
          loading: false,
          error: false,
          data: res.data.result_list,
        });
      })
      .catch((error) => {
        setActiveJobMesList({ loading: false, error: true, data: [] });
      });
  };

  useEffect(() => {
    if (!state) {
      navigate("/", { replace: true });
      return;
    }
    setDetails(state);
    getActiveJobMesList();
  }, [activeJobMesListReload]);

  return (
    <ActiveJobs
      details={state}
      activeJobMesList={activeJobMesList}
      reloadActiveJobList={setActiveJobMesListReload}
    />
  );
}

export default ManageActiveJobs;
