import { notification } from "antd";
import moment from "moment";
import React, { useState } from "react";
import { useMutation } from "react-apollo";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_APPOINTMENT } from "../../graphql/appointments.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import ScheduleAppointmentModalComponent from "./schedule-appointment-modal.component";

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

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

  return (
    <ScheduleAppointmentModalComponent
      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 => {
            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
              })
            });
          });
      }}
    />
  );
});
