import { notification } from "antd";
import React, { useState } from "react";
import { useMutation, useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import { withRouter } from "react-router-dom";
import { DELETE_ALL_AVAILABLE_NEW_JOBS, QUERY_AVAILABLE_NEW_JOBS } from "../../graphql/available-jobs.queries";
import { INSERT_NEW_JOB } from "../../graphql/jobs.queries";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobsAvailableComponent from "./jobs-available-new.component";

export default withRouter(function JobsAvailableContainer({
  deleteJob,
  estDataLazyLoad,
  history
}) {
  const { loading, error, data, refetch } = useQuery(QUERY_AVAILABLE_NEW_JOBS, {
    fetchPolicy: "network-only"
  });

  const { t } = useTranslation();

  const [modalVisible, setModalVisible] = useState(false);
  const [selectedOwner, setSelectedOwner] = useState(null);
  const [insertLoading, setInsertLoading] = useState(false);
  const [deleteAllNewJobs] = useMutation(DELETE_ALL_AVAILABLE_NEW_JOBS);
  const [insertNewJob] = useMutation(INSERT_NEW_JOB);
  const [loadEstData, estData] = estDataLazyLoad;

  const onModalOk = () => {
    setModalVisible(false);
    setInsertLoading(true);

    if (
      !(
        estData.data &&
        estData.data.available_jobs_by_pk &&
        estData.data.available_jobs_by_pk.est_data
      )
    ) {
      //We don't have the right data. Error!
      setInsertLoading(false);
      notification["error"]({
        message: t("jobs.errors.creating", { error: "No job data present." })
      });
    } else {
      insertNewJob({
        variables: {
          job: selectedOwner
            ? Object.assign(
                {},
                estData.data.available_jobs_by_pk.est_data,
                { owner: null },
                { ownerid: selectedOwner }
              )
            : estData.data.available_jobs_by_pk.est_data
        }
      })
        .then(r => {
          notification["success"]({
            message: t("jobs.successes.created"),
            onClick: () => {
              console.log("r", r);
              history.push(
                `/manage/jobs/${r.data.insert_jobs.returning[0].id}`
              );
            }
          });
          //Job has been inserted. Clean up the available jobs record.
          deleteJob({
            variables: { id: estData.data.available_jobs_by_pk.id }
          }).then(r => {
            refetch();
            setInsertLoading(false);
          });
        })
        .catch(r => {
          //error while inserting
          notification["error"]({
            message: t("jobs.errors.creating", { error: r.message })
          });
          refetch();
          setInsertLoading(false);
        });
    }
  };

  const onModalCancel = () => {
    setModalVisible(false);
    setSelectedOwner(null);
  };

  if (error) return <AlertComponent type="error" message={error.message} />;
  return (
    <LoadingSpinner
      loading={insertLoading}
      message={t("jobs.labels.creating_new_job")}
    >
      <JobsAvailableComponent
        loading={loading}
        data={data}
        refetch={refetch}
        deleteJob={deleteJob}
        deleteAllNewJobs={deleteAllNewJobs}
        insertNewJob={insertNewJob}
        estDataLazyLoad={estDataLazyLoad}
        onModalCancel={onModalCancel}
        onModalOk={onModalOk}
        modalVisible={modalVisible}
        setModalVisible={setModalVisible}
        selectedOwner={selectedOwner}
        setSelectedOwner={setSelectedOwner}
        loadEstData={loadEstData}
        estData={estData}
      />
    </LoadingSpinner>
  );
});
