import { Form, Modal, notification } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectCourtesyCarReturn } from "../../redux/modals/modals.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CourtesyCarReturnModalComponent from "./courtesy-car-return-modal.component";
import moment from "moment";
import { RETURN_CONTRACT } from "../../graphql/cccontracts.queries";
import { useMutation } from "@apollo/client";

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

const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("courtesyCarReturn")),
});

export function CCReturnModalContainer({
  courtesyCarReturnModal,
  toggleModalVisible,
  bodyshop,
}) {
  const [loading, setLoading] = useState(false);
  const { visible, context, actions } = courtesyCarReturnModal;
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [updateContract] = useMutation(RETURN_CONTRACT);
  const handleFinish = (values) => {
    setLoading(true);
    updateContract({
      variables: {
        contractId: context.contractId,
        cccontract: {
          kmend: values.kmend,
          actualreturn: values.actualreturn,
          status: "contracts.status.returned",
          fuelin: values.fuelin,
        },
        courtesycarid: context.courtesyCarId,
        courtesycar: {
          status: "courtesycars.status.in",
          fuel: values.fuelin,
          mileage: values.kmend,
        },
      },
    })
      .then((r) => {
        if (actions.refetch) actions.refetch();
        toggleModalVisible();
      })
      .catch((error) => {
        notification["error"]({
          message: t("contracts.errors.returning", { error: error }),
        });
      });
    setLoading(false);
  };

  return (
    <Modal
      title={t("courtesycars.labels.return")}
      visible={visible}
      onCancel={() => toggleModalVisible()}
      width={"90%"}
      okText={t("general.actions.save")}
      onOk={() => form.submit()}
      okButtonProps={{ htmlType: "submit", loading: loading }}
    >
      <Form
        form={form}
        onFinish={handleFinish}
        initialValues={{ fuel: 100, actualreturn: moment(new Date()) }}
      >
        <CourtesyCarReturnModalComponent />
      </Form>
    </Modal>
  );
}

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