import { Form, 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";
import JobDetailFormContext from "./jobs-detail.page.context";

function JobsDetailPageContainer({ match, form }) {
  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 [updateJobStatus] = useMutation(UPDATE_JOB_STATUS);
  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]);

  const handleSubmit = e => {
    e.preventDefault();

    form.validateFieldsAndScroll((err, values) => {
      if (err) {
        notification["error"]({
          message: t("jobs.errors.validationtitle"),
          description: t("jobs.errors.validation")
        });
      }
      if (!err) {
        mutationUpdateJob({
          variables: { jobId: data.jobs_by_pk.id, job: values }
        }).then(r => {
          notification["success"]({
            message: t("jobs.successes.savetitle")
          });
          //TODO: Better way to reset the field decorators?
          refetch().then(r => form.resetFields());
        });
      }
    });
  };

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

  return data.jobs_by_pk ? (
    <JobDetailFormContext.Provider value={form}>
      <JobsDetailPage
        job={data.jobs_by_pk}
        mutationUpdateJob={mutationUpdateJob}
        mutationConvertJob={mutationConvertJob}
        handleSubmit={handleSubmit}
        getFieldDecorator={form.getFieldDecorator}
        refetch={refetch}
        scheduleModalState={scheduleModalState}
        updateJobStatus={updateJobStatus}
      />
    </JobDetailFormContext.Provider>
  ) : (
    <AlertComponent message={t("jobs.errors.noaccess")} type="error" />
  );
}
export default Form.create({ name: "JobsDetailPageContainer" })(
  JobsDetailPageContainer
);
