import { Form, Modal } from "antd";
import { 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 CourtesyCarReturnModalComponent from "./courtesy-car-return-modal.component";
import dayjs from "../../utils/day";
import { RETURN_CONTRACT } from "../../graphql/cccontracts.queries";
import { useMutation } from "@apollo/client/react";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

export function CCReturnModalContainer({ courtesyCarReturnModal, toggleModalVisible }) {
  const [loading, setLoading] = useState(false);
  const { open, context, actions } = courtesyCarReturnModal;
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [updateContract] = useMutation(RETURN_CONTRACT);
  const notification = useNotification();

  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(() => {
        if (actions.refetch) actions.refetch();
        toggleModalVisible();
      })
      .catch((error) => {
        notification.error({
          title: t("contracts.errors.returning", { error: error })
        });
      });
    setLoading(false);
  };

  return (
    <Modal
      title={t("courtesycars.labels.return")}
      open={open}
      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: dayjs(new Date()) }}>
        <CourtesyCarReturnModalComponent />
      </Form>
    </Modal>
  );
}

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