import { gql, useMutation } from "@apollo/client";
import { Button, notification } from "antd";
import React, { useState } 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 {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

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

export function PaymentMarkSelectedExported({
  bodyshop,
  currentUser,
  paymentIds,
  disabled,
  loadingCallback,
  completedCallback,
  refetch,
}) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [insertExportLog] = useMutation(INSERT_EXPORT_LOG);
  const [updatePayments] = useMutation(gql`
    mutation UPDATE_PAYMENTS($paymentIds: [uuid!]!, $exportedat: timestamptz!) {
      update_payments(
        where: { id: { _in: $paymentIds } }
        _set: { exportedat: $exportedat }
      ) {
        returning {
          id
          exportedat
        }
      }
    }
  `);

  const handleUpdate = async () => {
    setLoading(true);
    loadingCallback(true);
    const result = await updatePayments({
      variables: { paymentIds: paymentIds, exportedat: new Date() },
      update(cache) {},
    });

    await insertExportLog({
      variables: {
        logs: paymentIds.map((id) => {
          return {
            bodyshopid: bodyshop.id,
            paymentid: id,
            successful: true,
            message: JSON.stringify([t("general.labels.markedexported")]),
            useremail: currentUser.email,
          };
        }),
      },
    });

    if (!result.errors) {
      notification["success"]({
        message: t("payments.successes.markexported"),
      });
    } else {
      notification["error"]({
        message: t("bills.errors.saving", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    loadingCallback(false);
    completedCallback && completedCallback([]);
    setLoading(false);
    refetch && refetch();
  };

  return (
    <Button loading={loading} disabled={disabled} onClick={handleUpdate}>
      {t("bills.labels.markexported")}
    </Button>
  );
}
