import { gql } from "@apollo/client";
import { useMutation } from "@apollo/client/react";
import { Button, Popconfirm } from "antd";
import { 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";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { isFunction } from "lodash";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser
});
const mapDispatchToProps = () => ({
  //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 [open, setOpen] = useState(false);
  const notification = useNotification();

  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() {
        // NO OP
      }
    });

    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({
        title: t("payments.successes.markexported")
      });
    } else {
      notification.error({
        title: t("bills.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    loadingCallback(false);

    if (isFunction(completedCallback)) {
      completedCallback([]);
    }

    setLoading(false);

    if (isFunction(refetch)) {
      refetch();
    }
    setOpen(false);
  };

  return (
    <Popconfirm
      open={open}
      title={t("general.labels.areyousure")}
      onCancel={() => setOpen(false)}
      onConfirm={handleUpdate}
      disabled={disabled}
    >
      <Button loading={loading} disabled={disabled} onClick={() => setOpen(true)} type="primary" danger>
        {t("bills.labels.markexported")}
      </Button>
    </Popconfirm>
  );
}
