import { DeleteFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Button, Popconfirm } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { DELETE_BILL } from "../../graphql/bills.queries";
import RbacWrapper from "../rbac-wrapper/rbac-wrapper.component";
import { insertAuditTrail } from "../../redux/application/application.actions";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

export function BillDeleteButton({ bill, jobid, callback, insertAuditTrail }) {
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();
  const [deleteBill] = useMutation(DELETE_BILL);
  const notification = useNotification();

  const handleDelete = async () => {
    setLoading(true);
    const result = await deleteBill({
      variables: { billId: bill.id },
      update(cache, { errors }) {
        if (errors) return;
        cache.modify({
          fields: {
            bills(existingBills, { readField }) {
              return existingBills.filter((billref) => bill.id !== readField("id", billref));
            },
            search_bills(existingBills, { readField }) {
              return existingBills.filter((billref) => bill.id !== readField("id", billref));
            }
          }
        });
      }
    });

    if (!result.errors) {
      notification.success({ title: t("bills.successes.deleted") });
      insertAuditTrail({
        jobid: jobid,
        operation: AuditTrailMapping.billdeleted(bill.invoice_number),
        type: "billdeleted"
      });

      if (callback && typeof callback === "function") callback(bill.id);
    } else {
      //Check if it's an fkey violation.
      const error = JSON.stringify(result.errors);

      if (error.toLowerCase().includes("inventory_billid_fkey")) {
        notification.error({
          title: t("bills.errors.deleting", {
            error: t("bills.errors.existinginventoryline")
          })
        });
      } else {
        notification.error({
          title: t("bills.errors.deleting", {
            error: JSON.stringify(result.errors)
          })
        });
      }
    }

    setLoading(false);
  };

  return (
    <RbacWrapper action="bills:delete" noauth={<></>}>
      <Popconfirm disabled={bill.exported} onConfirm={handleDelete} title={t("bills.labels.deleteconfirm")}>
        <Button icon={<DeleteFilled />} disabled={bill.exported} loading={loading} />
      </Popconfirm>
    </RbacWrapper>
  );
}
