import { useMutation } from "@apollo/client/react";
import { Button } from "antd";
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 { selectPayment } from "../../redux/modals/modals.selectors";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

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

  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.success({
        key: "paymentsuccessmarkforexport",
        title: t("payments.successes.markexported")
      });
      setPaymentContext({
        actions: {
          refetch
        },
        context: {
          ...paymentModal.context,
          ...paymentModal.context,
          ...payment,
          smartRefetch: true,
          exportedat: today
        }
      });

      if (refetch) {
        if (paymentModal.context.refetchRequiresContext) {
          refetch(paymentUpdateResponse && paymentUpdateResponse.data.update_payments.returning[0]);
        } else {
          refetch();
        }
      }
    } else {
      notification.error({
        title: 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);
