import { useMutation } from "@apollo/client/react";
import { gql } from "@apollo/client";
import { Button } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectAuthLevel, selectBodyshop } from "../../redux/user/user.selectors";
import { HasRbacAccess } from "../rbac-wrapper/rbac-wrapper.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { insertAuditTrail } from "../../redux/application/application.actions.js";
import AuditTrailMapping from "../../utils/AuditTrailMappings.js";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  authLevel: selectAuthLevel
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

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

export function BillMarkForReexportButton({ bodyshop, authLevel, bill, insertAuditTrail }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const notification = useNotification();

  const [updateBill] = useMutation(gql`
    mutation UPDATE_BILL($billId: uuid!) {
      update_bills(where: { id: { _eq: $billId } }, _set: { exported: false }) {
        returning {
          id
          exported
          exported_at
        }
      }
    }
  `);

  const handleUpdate = async () => {
    setLoading(true);
    const result = await updateBill({
      variables: { billId: bill.id }
    });

    if (!result.errors) {
      notification.success({
        title: t("bills.successes.reexport")
      });
      insertAuditTrail({
        jobid: bill.jobid,
        billid: bill.id,
        operation: AuditTrailMapping.billmarkforreexport(bill.invoice_number),
        type: "billmarkforreexport"
      });
    } else {
      notification.error({
        title: t("bills.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
    //Get the owner details, populate it all back into the job.
  };

  const hasAccess = HasRbacAccess({
    bodyshop,
    authLevel,
    action: "bills:reexport"
  });

  if (hasAccess)
    return (
      <Button loading={loading} disabled={!bill.exported} onClick={handleUpdate}>
        {t("bills.labels.markforreexport")}
      </Button>
    );

  return <></>;
}
