import React, { useState } from "react";
import ScheduleJobModalComponent from "./schedule-job-modal.component";
import { useMutation, useQuery } from "react-apollo";
import {
  INSERT_APPOINTMENT,
  QUERY_APPOINTMENTS_BY_JOBID
} from "../../graphql/appointments.queries";
import moment from "moment";
import { notification } from "antd";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB_STATUS } from "../../graphql/jobs.queries";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

export default connect(
  mapStateToProps,
  null
)(function ScheduleJobModalContainer({
  scheduleModalState,
  jobId,
  bodyshop,
  refetch
}) {
  const [scheduleModalVisible, setscheduleModalVisible] = scheduleModalState;
  const [appData, setAppData] = useState({
    jobid: jobId,
    start: null,
    bodyshopid: bodyshop.id
  });
  const [insertAppointment] = useMutation(INSERT_APPOINTMENT);
  const [updateJobStatus] = useMutation(UPDATE_JOB_STATUS, {
    variables: {
      jobId: jobId,
      status: bodyshop.md_ro_statuses.default_scheduled
    }
  });
  const [formData, setFormData] = useState({ notifyCustomer: false });
  const { t } = useTranslation();

  const existingAppointments = useQuery(QUERY_APPOINTMENTS_BY_JOBID, {
    variables: { jobid: jobId },
    fetchPolicy: "network-only",
    skip: !scheduleModalVisible
  });

  return (
    <ScheduleJobModalComponent
      existingAppointments={existingAppointments}
      appData={appData}
      setAppData={setAppData}
      formData={formData}
      setFormData={setFormData}
      //Spreadable Modal Props
      visible={scheduleModalVisible}
      onCancel={() => setscheduleModalVisible(false)}
      onOk={() => {
        //TODO Customize the amount of minutes it will add.
        insertAppointment({
          variables: {
            app: { ...appData, end: moment(appData.start).add(60, "minutes") }
          }
        })
          .then(r => {
            updateJobStatus().then(r => {
              notification["success"]({
                message: t("appointments.successes.created")
              });

              if (formData.notifyCustomer) {
                //TODO Implement customer reminder on scheduling.
                alert("Chosed to notify the customer somehow!");
              }
              setscheduleModalVisible(false);
              if (refetch) refetch();
            });
          })
          .catch(error => {
            notification["error"]({
              message: t("appointments.errors.saving", {
                message: error.message
              })
            });
          });
      }}
    />
  );
});
