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

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

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  scheduleModal: selectSchedule,
});
const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("schedule")),
});
export function ScheduleJobModalContainer({
  scheduleModal,
  bodyshop,
  toggleModalVisible,
}) {
  const { visible, context, actions } = scheduleModal;
  const { jobId } = context;
  const { refetch } = actions;

  const [appData, setAppData] = useState({
    start: null,
  });
  const [insertAppointment] = useMutation(INSERT_APPOINTMENT);
  const [updateJobStatus] = useMutation(UPDATE_JOBS);
  const [formData, setFormData] = useState({ notifyCustomer: false });
  const { t } = useTranslation();

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

  //TODO Customize the amount of minutes it will add.
  const handleOk = () => {
    insertAppointment({
      variables: {
        app: {
          ...appData,
          jobid: jobId,
          bodyshopid: bodyshop.id,
          end: moment(appData.start).add(60, "minutes"),
        },
      },
    })
      .then((r) => {
        updateJobStatus({
          variables: {
            jobIds: [jobId],
            fields: {
              status: bodyshop.md_ro_statuses.default_scheduled,
              date_scheduled: new Date(),
              scheduled_in: appData.start,
            },
          },
        }).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!");
          }
          toggleModalVisible();
          if (refetch) refetch();
        });
      })
      .catch((error) => {
        notification["error"]({
          message: t("appointments.errors.saving", {
            message: error.message,
          }),
        });
      });
  };

  return (
    <Modal
      visible={visible}
      onCancel={() => toggleModalVisible()}
      onOk={handleOk}
      width={"90%"}
      maskClosable={false}
      destroyOnClose
      okButtonProps={{ disabled: appData.start ? false : true }}
    >
      <ScheduleJobModalComponent
        existingAppointments={existingAppointments}
        appData={appData}
        setAppData={setAppData}
        formData={formData}
        setFormData={setFormData}
      />
    </Modal>
  );
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ScheduleJobModalContainer);
