import { useMutation } from "@apollo/client";
import { Button, notification } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_EXPORT_LOG } from "../../graphql/accounting.queries";
import { UPDATE_PAYMENT } from "../../graphql/payments.queries";
import { setModalContext } from "../../redux/modals/modals.actions";
import { selectCurrentUser } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
});

const mapDispatchToProps = (dispatch) => ({
  setPaymentContext: (context) =>
    dispatch(setModalContext({ context: context, modal: "payment" })),
});

const PaymentMarkForExportButton = ({
  bodyshop,
  payment,
  refetch,
  setPaymentContext,
  currentUser,
}) => {
  const { t } = useTranslation();
  const [insertExportLog, { loading: exportLogLoading }] =
    useMutation(INSERT_EXPORT_LOG);
  const [updatePayment, { loading: updatePaymentLoading }] =
    useMutation(UPDATE_PAYMENT);

  const handleClick = async () => {
    const today = new Date();

    await insertExportLog({
      variables: {
        logs: [
          {
            bodyshopid: bodyshop.id,
            paymentid: payment.id,
            successful: true,
            useremail: currentUser.email,
          },
        ],
      },
    });
    const paymentUpdateResponse = await updatePayment({
      variables: {
        paymentId: payment.id,
        payment: {
          exportedat: today,
        },
      },
    });
    if (!!!paymentUpdateResponse.errors) {
      notification.open({
        type: "success",
        key: "paymentsuccessmarkforexport",
        message: t("payments.successes.markexported"),
      });
      setPaymentContext({
        actions: {
          refetch,
        },
        context: {
          ...payment,
          exportedat: today,
        },
      });

      if (refetch)
        refetch(
          paymentUpdateResponse &&
            paymentUpdateResponse.data.update_payments.returning[0]
        );
    } else {
      notification["error"]({
        message: t("payments.errors.exporting", {
          error: JSON.stringify(paymentUpdateResponse.error),
        }),
      });
    }
  };

  return (
    <Button
      onClick={handleClick}
      loading={exportLogLoading || updatePaymentLoading}
      disabled={!!payment.exportedat}
    >
      {t("payments.labels.markexported")}
    </Button>
  );
};

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