'use strict';

var index = require('./index-p7cvUYAE.js');
require('./config-state-BIgGhhe9.js');
require('./dinero-BwNN_k7x.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var Pagination = require('./Pagination-Dediz133.js');
require('./Business-oBifyXkW.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var utils = require('./utils-BsnepLy6.js');
var payment_service = require('./payment.service-8Q-EEtXL.js');
var table = require('./table-DjbNv28p.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
var eventTypes = require('./event-types-YOY5TKUN.js');
var utils$1 = require('./utils-CYONRFR6.js');
var parts = require('./parts-BXshb_S-.js');
require('./index-W-zoNiyM.js');
require('./package-YyJzVqrh.js');
require('./Api-D9vOcUw4.js');
require('./spinner-C6ZGOB2P.js');

const makeGetPaymentTransactions = ({ id, authToken, service }) => async ({ params, onSuccess, onError, final }) => {
    var _a;
    try {
        const response = await service.fetchPaymentTransactions(id, authToken, params);
        if (!response.error) {
            const balanceTransactions = response.data.map((dataItem) => new Plaid.PaymentBalanceTransaction(dataItem));
            const pagingInfo = Object.assign({}, response.page_info);
            onSuccess({ balanceTransactions, pagingInfo });
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        onError({
            error: utils.getErrorMessage(error),
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};

const defaultColumnsKeys = 'created_at,type,id,amount,balance';
const paymentTransactionTableColumns = {
    created_at: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The date and time each transaction was made" }, "Processed On")),
    type: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The type of each transaction" }, "Type")),
    id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The unique identifier of each transaction" }, "ID")),
    amount: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The dollar amount of each transaction", class: "text-end" }, "Amount")),
    balance: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The running total amount of this payment that belongs to you", class: "text-end" }, "Balance")),
    currency: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The currency of each transaction" }, "Currency")),
    financial_transaction_id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The unique identifier of the financial transaction associated with the payment balance transaction" }, "Financial Transaction ID")),
    payment_id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The unique identifier of the payment associated with the payment balance transaction" }, "Payment ID")),
    payment_balance_txn_type: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The type of the payment balance transaction" }, "Transaction Type")),
    source_id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The unique identifier of the source object associated with the payment balance transaction" }, "Source ID")),
    source_type: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The type of the source object associated with the payment balance transaction" }, "Source Type")),
};
const paymentTransactionTypes = {
    ach_return: "ACH Return",
    ach_return_fee: "ACH Return Fee",
    dispute: "Dispute",
    dispute_fee: "Dispute Fee",
    dispute_fee_refund: "Dispute Fee Refund",
    dispute_refund: "Dispute Refund",
    payment: "Payment",
    payment_fee: "Fee",
    platform_fee: "Platform Fee",
    platform_fee_return: "Platform Fee Return",
    processing_fee: "Processing Fee",
    processing_fee_return: "Processing Fee Return",
    refund: "Refund",
    fee_refund: "Fee Refund",
    application_fee_returned: "Application Fee Returned",
    refund_failure: "Refund Failure",
    void: "Void",
};
const paymentTransactionTableCells = {
    created_at: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("div", { class: "fw-bold" }, utils$1.convertToLocal(balanceTransaction.created_at, { showDisplayDate: true })), index.h("div", { class: "fw-bold" }, utils$1.convertToLocal(balanceTransaction.created_at, { showTime: true })))),
    type: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, paymentTransactionTypes[balanceTransaction.payment_balance_txn_type])),
    id: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.id)),
    amount: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1), class: "text-end" }, balanceTransaction.formattedPaymentAmount(balanceTransaction.amount))),
    balance: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1), class: "text-end" }, balanceTransaction.formattedPaymentAmount(balanceTransaction.balance))),
    currency: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.currency)),
    financial_transaction_id: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.financial_transaction_id)),
    payment_id: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.payment_id)),
    payment_balance_txn_type: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.payment_balance_txn_type)),
    source_id: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.source_id)),
    source_type: (balanceTransaction, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, balanceTransaction.source_type)),
};

const JustifiPaymentTransactionsList = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.balanceTransactions = [];
        this.isLoading = true;
        this.errorMessage = null;
        this.paging = Pagination.pagingDefaults;
        this.pagingParams = {};
        this.columns = defaultColumnsKeys;
        this.handleClickPrevious = (beforeCursor) => {
            this.pagingParams = { before_cursor: beforeCursor };
            this.clickEvent.emit({ name: eventTypes.TableClickActions.previous });
        };
        this.handleClickNext = (afterCursor) => {
            this.pagingParams = { after_cursor: afterCursor };
            this.clickEvent.emit({ name: eventTypes.TableClickActions.next });
        };
        this.rowClickHandler = (e) => {
            const clickedPaymentID = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedPaymentID)
                return;
            const transactionData = this.balanceTransactions.find((payment) => payment.id === clickedPaymentID);
            this.clickEvent.emit({ name: eventTypes.TableClickActions.row, data: transactionData });
        };
    }
    componentWillLoad() {
        this.transactionsTable = new table.Table(this.balanceTransactions, this.columns, paymentTransactionTableColumns, paymentTransactionTableCells);
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.initializeApi();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    ;
    propChanged() {
        this.initializeApi();
    }
    handleError(code, errorMessage, severity) {
        this.isLoading = false;
        this.errorEvent.emit({ errorCode: code, message: errorMessage, severity });
    }
    initializeApi() {
        if (this.paymentId && this.authToken) {
            const getPaymentTransactions = makeGetPaymentTransactions({
                id: this.paymentId,
                authToken: this.authToken,
                service: new payment_service.PaymentService()
            });
            getPaymentTransactions({
                params: this.pagingParams,
                onSuccess: ({ balanceTransactions, pagingInfo }) => {
                    this.balanceTransactions = balanceTransactions;
                    this.paging = pagingInfo;
                    this.transactionsTable.collectionData = this.balanceTransactions;
                },
                onError: ({ error, code, severity }) => {
                    this.errorMessage = error.message;
                    this.handleError(error, code, severity);
                },
                final: () => {
                    this.isLoading = false;
                }
            });
        }
        else {
            this.errorMessage = 'payment-id and auth-token props are required';
            this.handleError(Plaid.ComponentErrorCodes.MISSING_PROPS, this.errorMessage, Plaid.ComponentErrorSeverity.ERROR);
        }
    }
    get entityId() {
        return this.balanceTransactions.map((transaction) => transaction.id);
    }
    get showEmptyState() {
        return !this.isLoading && !this.errorMessage && this.transactionsTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.isLoading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.isLoading;
    }
    render() {
        return (index.h(styledHost.StyledHost, { key: '24e7a4313ab91f179fd27b6596f012487de06815' }, index.h(table.TableWrapper, { key: '1f9a7a56a940e41dd865bc6f3a8681ce86d60d58' }, index.h(table.TableComponent, { key: 'a26ce09ae4df84698be1ea37cb735e38c0a0402e' }, index.h(table.TableHead, { key: '07f8655efd483e1d9240e65b17dc13583028f376' }, index.h(table.TableHeadRow, { key: '0b62a7700715dbaffbedc0538432d075a3158499' }, this.transactionsTable.columnData.map((column) => column))), index.h(table.TableBody, { key: 'adf75fa50ddfb5257875b2779fc6c157812d4c19' }, index.h(table.TableLoadingState, { key: 'bc77de512b3e5fd1e6c4b8cf908b46027a3bc33f', columnSpan: this.transactionsTable.columnKeys.length, isLoading: this.isLoading }), index.h(table.TableEmptyState, { key: '413d46e184399cba3993f37efd64cb0d0a10d905', isEmpty: this.showEmptyState, columnSpan: this.transactionsTable.columnKeys.length }), index.h(table.TableErrorState, { key: '9deaa794dc848ed7c85cbadc3b4cfe7c9fb1176f', columnSpan: this.transactionsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.transactionsTable.rowData.map((data, index$1) => (index.h(table.TableRow, { "data-test-id": "table-row", "data-row-entity-id": this.entityId[index$1], onClick: this.rowClickHandler }, data)))), this.paging && (index.h(table.TableFoot, { key: '16ca0811bf42dc9419f8b77086e8e7e2cf6d0085' }, index.h(table.TableFootRow, { key: 'e11be42549832c35078acf47b7c165fe1e50ea98' }, index.h(table.TableFootCell, { key: '205d649068b84200b88adc1be9cfe192abfe13be', colSpan: this.transactionsTable.columnData.length }, index.h("pagination-menu", { key: '2a28645220d4f18b7037e461bd93eefc3aed49a0', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "pagingParams": ["propChanged"],
        "paymentId": ["propChanged"],
        "authToken": ["propChanged"]
    }; }
};

exports.justifi_payment_transactions_list = JustifiPaymentTransactionsList;
