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 { selectAuthLevel, selectBodyshop } from "../../redux/user/user.selectors";
import { HasRbacAccess } from "../rbac-wrapper/rbac-wrapper.component";

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

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

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

  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"]({
        message: t("bills.successes.reexport")
      });
    } else {
      notification["error"]({
        message: 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 <></>;
}
