import { notification } from "antd";
import React, { useEffect, useState } from "react";
import { useMutation, useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import AlertComponent from "../../components/alert/alert.component";
import SpinComponent from "../../components/loading-spinner/loading-spinner.component";
import {
  CONVERT_JOB_TO_RO,
  GET_JOB_BY_PK,
  UPDATE_JOB,
  UPDATE_JOB_STATUS
} from "../../graphql/jobs.queries";
import JobsDetailPage from "./jobs-detail.page.component";

function JobsDetailPageContainer({ match }) {
  const { jobId } = match.params;
  const { t } = useTranslation();

  const scheduleModalState = useState(false);

  const { loading, error, data, refetch } = useQuery(GET_JOB_BY_PK, {
    variables: { id: jobId },
    fetchPolicy: "network-only"
  });
  const [mutationUpdateJob] = useMutation(UPDATE_JOB);
  const [mutationConvertJob] = useMutation(CONVERT_JOB_TO_RO);
  const [mutationUpdateJobstatus] = useMutation(UPDATE_JOB_STATUS);

  const updateJobStatus = status => {
    mutationUpdateJobstatus({
      variables: { jobId: jobId, status: status }
    })
      .then(r => {
        notification["success"]({ message: t("jobs.successes.save") });
        refetch();
      })
      .catch(error => {
        notification[error]({ message: t("jobs.errors.saving") });
      });
  };

  useEffect(() => {
    document.title = loading
      ? t("titles.app")
      : error
      ? t("titles.app")
      : t("titles.jobsdetail", {
          ro_number: data.jobs_by_pk.converted
            ? data.jobs_by_pk.ro_number
            : `EST ${data.jobs_by_pk.est_number}`
        });
  }, [loading, data, t, error]);

  if (loading) return <SpinComponent />;
  if (error) return <AlertComponent message={error.message} type="error" />;

  return data.jobs_by_pk ? (
    <JobsDetailPage
      job={data.jobs_by_pk}
      mutationConvertJob={mutationConvertJob}
      mutationUpdateJob={mutationUpdateJob}
      refetch={refetch}
      scheduleModalState={scheduleModalState}
      updateJobStatus={updateJobStatus}
    />
  ) : (
    <AlertComponent message={t("jobs.errors.noaccess")} type="error" />
  );
}
export default JobsDetailPageContainer;
