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_SUPPLEMENT_JOBS,
  QUERY_AVAILABLE_SUPPLEMENT_JOBS
} from "../../graphql/available-jobs.queries";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import AlertComponent from "../alert/alert.component";
import JobsAvailableSupplementComponent from "./jobs-available-supplement.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";

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

  const [deleteAllNewJobs] = useMutation(DELETE_ALL_AVAILABLE_SUPPLEMENT_JOBS);

  const [modalVisible, setModalVisible] = useState(false);
  const [selectedJob, setSelectedJob] = useState(null);
  const [insertLoading, setInsertLoading] = useState(false);
  const [updateJob] = useMutation(UPDATE_JOB);
  const [loadEstData, estData] = estDataLazyLoad;
  const importOptionsState = useState({ overrideHeaders: false });
  const importOptions = importOptionsState[0];
  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 {
      //create upsert job
      let supp = estData.data.available_jobs_by_pk.est_data;
      delete supp.joblines;
      //TODO How to update the estimate lines.
      delete supp.owner;
      delete supp.vehicle;

      if (!importOptions.overrideHeaders) {
        delete supp["ins_ea"];
        //TODO Remove all required fields.
      }

      updateJob({
        variables: {
          jobId: selectedJob,
          job: supp
        }
      })
        .then(r => {
          notification["success"]({
            message: t("jobs.successes.supplemented"),
            onClick: () => {
              history.push(
                `/manage/jobs/${r.data.update_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);
    setSelectedJob(null);
  };

  if (error) return <AlertComponent type='error' message={error.message} />;
  return (
    <LoadingSpinner
      loading={insertLoading}
      message={t("jobs.labels.creating_new_job")}>
      <JobsAvailableSupplementComponent
        loading={loading}
        data={data}
        refetch={refetch}
        deleteJob={deleteJob}
        updateJob={updateJob}
        onModalOk={onModalOk}
        onModalCancel={onModalCancel}
        modalVisible={modalVisible}
        setModalVisible={setModalVisible}
        selectedJob={selectedJob}
        setSelectedJob={setSelectedJob}
        deleteAllNewJobs={deleteAllNewJobs}
        loadEstData={loadEstData}
        estData={estData}
        importOptionsState={importOptionsState}
      />
    </LoadingSpinner>
  );
});
