import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import { c as configState } from './config-state.js';
import './dinero.js';
import { p as PayoutBalanceTransaction, 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 PayoutService } from './payout.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 makeGetPayoutTransactions = ({ accountId, authToken, service }) => async ({ params, onSuccess, onError, final }) => {
    var _a;
    try {
        const response = await service.fetchPayoutTransactions(accountId, authToken, params);
        if (!response.error) {
            const balanceTransactions = response.data.map((dataItem) => new PayoutBalanceTransaction(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,txn_type,description,amount,fee,net';
const payoutTransactionTableColumns = {
    id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of each transaction" }, "ID")),
    account_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of the account associated with each transaction" }, "Account ID")),
    payout_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of the payout associated with each transaction" }, "Payout ID")),
    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")),
    amount: () => (h("th", { part: tableHeadCell, scope: "col", title: "The dollar amount of each transaction" }, "Amount")),
    fee: () => (h("th", { part: tableHeadCell, scope: "col", title: "The fee associated with each transaction" }, "Fee")),
    net: () => (h("th", { part: tableHeadCell, scope: "col", title: "The net amount of each transaction" }, "Net")),
    currency: () => (h("th", { part: tableHeadCell, scope: "col", title: "The currency of each transaction" }, "Currency")),
    description: () => (h("th", { part: tableHeadCell, scope: "col", title: "The description of each transaction" }, "Description")),
    source_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The unique identifier of the source object associated with the payment balance transaction" }, "Source ID")),
    txn_type: () => (h("th", { part: tableHeadCell, scope: "col", title: "The type of each transaction" }, "Type")),
    created_at: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time each transaction was made" }, "Processed On")),
    available_on: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time each transaction will be available" }, "Available On")),
    updated_at: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time each transaction was last updated" }, "Updated On")),
};
const payoutTransactionTypes = {
    fee: "Fee",
    payment: "Payment",
    payout: "Payout",
    seller_payment_refund: "Seller Payment Refund",
    dispute_amount_collected: "Dispute Amount Collected",
    dispute_fee_collected: "Dispute Fee Collected",
    seller_payment: "Seller Payment",
    transfer: "Transfer",
    partner_platform_proceeds_credit: "Partner Platform Proceeds Credit",
    processing_fee: "Processing Fee",
    refund_processing_fee: "Refund Processing Fee",
    fee_rounding_adjustment: "Fee Rounding Adjustment",
    platform_fee: "Platform Fee",
    processing_fee_return: "Processing Fee Return",
    platform_fee_return: "Platform Fee Return"
};
const payoutTransactionTableCells = {
    id: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.id) }, transaction.id)),
    account_id: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.account_id) }, transaction.account_id)),
    payout_id: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.payout_id) }, transaction.payout_id)),
    financial_transaction_id: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.financial_transaction_id) }, transaction.financial_transaction_id)),
    amount: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.amount) }, transaction.formattedPaymentAmount(transaction.amount))),
    fee: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.fee) }, transaction.formattedPaymentAmount(transaction.fee))),
    net: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.net) }, transaction.formattedPaymentAmount(transaction.net))),
    currency: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.currency) }, transaction.currency)),
    description: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.description) }, transaction.description)),
    source_id: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.source_id) }, transaction.source_id)),
    txn_type: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.txn_type) }, payoutTransactionTypes[transaction.txn_type])),
    created_at: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.created_at) }, h("div", { class: "fw-bold" }, convertToLocal(transaction.created_at, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(transaction.created_at, { showTime: true })))),
    available_on: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.available_on) }, h("div", { class: "fw-bold" }, convertToLocal(transaction.available_on, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(transaction.available_on, { showTime: true })))),
    updated_at: (transaction) => (h("td", { part: getAlternateTableCellPart(transaction.updated_at) }, h("div", { class: "fw-bold" }, convertToLocal(transaction.updated_at, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(transaction.updated_at, { showTime: true })))),
};

const JustifiPayoutTransactionsList$1 = /*@__PURE__*/ proxyCustomElement(class JustifiPayoutTransactionsList 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 clickedPayoutId = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedPayoutId)
                return;
            const transactionData = this.balanceTransactions.find((payout) => payout.id === clickedPayoutId);
            this.clickEvent.emit({ name: TableClickActions.row, data: transactionData });
        };
    }
    componentWillLoad() {
        this.transactionsTable = new Table(this.balanceTransactions, this.columns, payoutTransactionTableColumns, payoutTransactionTableCells);
        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.payoutId && this.authToken) {
            const getPayoutTransactions = makeGetPayoutTransactions({
                accountId: configState.accountId,
                authToken: this.authToken,
                service: new PayoutService()
            });
            getPayoutTransactions({
                params: this.requestParams,
                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 = 'payout-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;
    }
    get requestParams() {
        return Object.assign({ payout_id: this.payoutId, limit: '15' }, this.pagingParams);
    }
    render() {
        return (h(StyledHost, { key: 'e7b5b219c34d1c8610fb4113fedd503f0512db2d' }, h(TableWrapper, { key: '97bbe678c90ba115a091db4fac42560c17f557f2' }, h(TableComponent, { key: 'ef90c77cd8f19a80e2b3e2b514aa1bc735a1b783' }, h(TableHead, { key: 'f5f0a00594f099931f1ac1cd4e359bb8fab11ec8' }, h(TableHeadRow, { key: '559648add19e0426d756f71ecb7bbd5cbcf1349e' }, this.transactionsTable.columnData.map((column) => column))), h(TableBody, { key: '49f8da0be5dba34ffbb92805d7b5b0fb3eeb6bf7' }, h(TableLoadingState, { key: '1d61dc2157608f38eb34e64452d7089857e6c67d', columnSpan: this.transactionsTable.columnKeys.length, isLoading: this.isLoading }), h(TableEmptyState, { key: 'd1f735fdb009740a186a16ea7e15d0320965a286', isEmpty: this.showEmptyState, columnSpan: this.transactionsTable.columnKeys.length }), h(TableErrorState, { key: 'f50ecc151be5c9143fb69d575a1ef14b3aa17b61', 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: '560536e623b2437d613169af2980aec13ebb4531' }, h(TableFootRow, { key: '42b82920fdd6056bb654db92acf3741aafb13d99' }, h(TableFootCell, { key: 'e2545104fdac51e0ada942138a08714f213bce63', colSpan: this.transactionsTable.columnData.length }, h("pagination-menu", { key: '6a74b19f3fa02f0e86e00783a06b0dfba2bc0ed8', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "pagingParams": ["propChanged"],
        "payoutId": ["propChanged"],
        "authToken": ["propChanged"]
    }; }
}, [257, "justifi-payout-transactions-list", {
        "payoutId": [1, "payout-id"],
        "authToken": [1, "auth-token"],
        "columns": [1],
        "balanceTransactions": [32],
        "transactionsTable": [32],
        "isLoading": [32],
        "errorMessage": [32],
        "paging": [32],
        "pagingParams": [32]
    }, undefined, {
        "pagingParams": ["propChanged"],
        "payoutId": ["propChanged"],
        "authToken": ["propChanged"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-payout-transactions-list", "pagination-menu"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-payout-transactions-list":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiPayoutTransactionsList$1);
            }
            break;
        case "pagination-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiPayoutTransactionsList = JustifiPayoutTransactionsList$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiPayoutTransactionsList, defineCustomElement };
