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

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"),
      });

      if (refetch) refetch();

      setPaymentContext({
        actions: {
          refetch,
        },
        context: {
          ...payment,
          exportedat: today,
        },
      });
    } 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);
