import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import './config-state.js';
import './dinero.js';
import { n as PaymentBalanceTransaction, C as ComponentErrorSeverity, a as ComponentErrorCodes } from './Plaid.js';
import { p as pagingDefaults } from './Pagination.js';
import './Business.js';
import './ApplePay.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { c as checkPkgVersion } from './check-pkg-version.js';
import { g as getErrorCode, a as getErrorMessage } from './utils3.js';
import { P as PaymentService } from './payment.service.js';
import { T as Table, a as TableWrapper, b as TableComponent, c as TableHead, d as TableHeadRow, e as TableBody, f as TableLoadingState, g as TableEmptyState, h as TableErrorState, i as TableRow, j as TableFoot, k as TableFootRow, l as TableFootCell } from './table.js';
import { S as StyledHost } from './styled-host.js';
import './justifi-details2.js';
import { T as TableClickActions } from './event-types.js';
import './justifi-radio-list-item2.js';
import { h as convertToLocal } from './utils2.js';
import { D as tableHeadCell, ah as getAlternateTableCellPart } from './parts.js';
import { d as defineCustomElement$2 } from './pagination-menu2.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 PaymentBalanceTransaction(dataItem));
            const pagingInfo = Object.assign({}, response.page_info);
            onSuccess({ balanceTransactions, pagingInfo });
        }
        else {
            const responseError = getErrorMessage(response.error);
            const code = getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            onError({
                error: responseError,
                code,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        onError({
            error: getErrorMessage(error),
            code,
            severity: ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};

const defaultColumnsKeys = 'created_at,type,id,amount,balance';
const paymentTransactionTableColumns = {
    created_at: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time each transaction was made" }, "Processed On")),
    type: () => (h("th", { part: tableHeadCell, scope: "col", title: "The type of each transaction" }, "Type")),
    id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of each transaction" }, "ID")),
    amount: () => (h("th", { part: tableHeadCell, scope: "col", title: "The dollar amount of each transaction", class: "text-end" }, "Amount")),
    balance: () => (h("th", { part: tableHeadCell, scope: "col", title: "The running total amount of this payment that belongs to you", class: "text-end" }, "Balance")),
    currency: () => (h("th", { part: tableHeadCell, scope: "col", title: "The currency of each transaction" }, "Currency")),
    financial_transaction_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of the financial transaction associated with the payment balance transaction" }, "Financial Transaction ID")),
    payment_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of the payment associated with the payment balance transaction" }, "Payment ID")),
    payment_balance_txn_type: () => (h("th", { part: tableHeadCell, scope: "col", title: "The type of the payment balance transaction" }, "Transaction Type")),
    source_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of the source object associated with the payment balance transaction" }, "Source ID")),
    source_type: () => (h("th", { part: 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) => (h("td", { part: getAlternateTableCellPart(index) }, h("div", { class: "fw-bold" }, convertToLocal(balanceTransaction.created_at, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(balanceTransaction.created_at, { showTime: true })))),
    type: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, paymentTransactionTypes[balanceTransaction.payment_balance_txn_type])),
    id: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.id)),
    amount: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index), class: "text-end" }, balanceTransaction.formattedPaymentAmount(balanceTransaction.amount))),
    balance: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index), class: "text-end" }, balanceTransaction.formattedPaymentAmount(balanceTransaction.balance))),
    currency: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.currency)),
    financial_transaction_id: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.financial_transaction_id)),
    payment_id: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.payment_id)),
    payment_balance_txn_type: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.payment_balance_txn_type)),
    source_id: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.source_id)),
    source_type: (balanceTransaction, index) => (h("td", { part: getAlternateTableCellPart(index) }, balanceTransaction.source_type)),
};

const JustifiPaymentTransactionsList$1 = /*@__PURE__*/ proxyCustomElement(class JustifiPaymentTransactionsList extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.clickEvent = createEvent(this, "click-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.balanceTransactions = [];
        this.isLoading = true;
        this.errorMessage = null;
        this.paging = pagingDefaults;
        this.pagingParams = {};
        this.columns = defaultColumnsKeys;
        this.handleClickPrevious = (beforeCursor) => {
            this.pagingParams = { before_cursor: beforeCursor };
            this.clickEvent.emit({ name: TableClickActions.previous });
        };
        this.handleClickNext = (afterCursor) => {
            this.pagingParams = { after_cursor: afterCursor };
            this.clickEvent.emit({ name: 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: TableClickActions.row, data: transactionData });
        };
    }
    componentWillLoad() {
        this.transactionsTable = new Table(this.balanceTransactions, this.columns, paymentTransactionTableColumns, paymentTransactionTableCells);
        checkPkgVersion();
        this.analytics = new 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 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(ComponentErrorCodes.MISSING_PROPS, this.errorMessage, 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 (h(StyledHost, { key: '24e7a4313ab91f179fd27b6596f012487de06815' }, h(TableWrapper, { key: '1f9a7a56a940e41dd865bc6f3a8681ce86d60d58' }, h(TableComponent, { key: 'a26ce09ae4df84698be1ea37cb735e38c0a0402e' }, h(TableHead, { key: '07f8655efd483e1d9240e65b17dc13583028f376' }, h(TableHeadRow, { key: '0b62a7700715dbaffbedc0538432d075a3158499' }, this.transactionsTable.columnData.map((column) => column))), h(TableBody, { key: 'adf75fa50ddfb5257875b2779fc6c157812d4c19' }, h(TableLoadingState, { key: 'bc77de512b3e5fd1e6c4b8cf908b46027a3bc33f', columnSpan: this.transactionsTable.columnKeys.length, isLoading: this.isLoading }), h(TableEmptyState, { key: '413d46e184399cba3993f37efd64cb0d0a10d905', isEmpty: this.showEmptyState, columnSpan: this.transactionsTable.columnKeys.length }), h(TableErrorState, { key: '9deaa794dc848ed7c85cbadc3b4cfe7c9fb1176f', columnSpan: this.transactionsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.transactionsTable.rowData.map((data, index) => (h(TableRow, { "data-test-id": "table-row", "data-row-entity-id": this.entityId[index], onClick: this.rowClickHandler }, data)))), this.paging && (h(TableFoot, { key: '16ca0811bf42dc9419f8b77086e8e7e2cf6d0085' }, h(TableFootRow, { key: 'e11be42549832c35078acf47b7c165fe1e50ea98' }, h(TableFootCell, { key: '205d649068b84200b88adc1be9cfe192abfe13be', colSpan: this.transactionsTable.columnData.length }, 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"]
    }; }
}, [257, "justifi-payment-transactions-list", {
        "paymentId": [1, "payment-id"],
        "authToken": [1, "auth-token"],
        "columns": [1],
        "balanceTransactions": [32],
        "transactionsTable": [32],
        "isLoading": [32],
        "errorMessage": [32],
        "paging": [32],
        "pagingParams": [32]
    }, undefined, {
        "pagingParams": ["propChanged"],
        "paymentId": ["propChanged"],
        "authToken": ["propChanged"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-payment-transactions-list", "pagination-menu"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-payment-transactions-list":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiPaymentTransactionsList$1);
            }
            break;
        case "pagination-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiPaymentTransactionsList = JustifiPaymentTransactionsList$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiPaymentTransactionsList, defineCustomElement };
