import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import { P as PaymentService } from './payment.service.js';
import './config-state.js';
import './dinero.js';
import { e as Payment, C as ComponentErrorSeverity, a as ComponentErrorCodes } from './Plaid.js';
import { p as pagingDefaults } from './Pagination.js';
import './Business.js';
import './ApplePay.js';
import { g as getErrorCode, a as getErrorMessage } from './utils3.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { c as checkPkgVersion } from './check-pkg-version.js';
import { S as StyledHost } from './styled-host.js';
import './justifi-details2.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 { T as TableClickActions } from './event-types.js';
import './justifi-radio-list-item2.js';
import { M as MapPaymentStatusToBadge } from './payments-status.js';
import { h as convertToLocal } from './utils2.js';
import { D as tableHeadCell, ah as getAlternateTableCellPart } from './parts.js';
import { o as onQueryParamsChange, g as getRequestParams } from './payments-list-params-state.js';
import { d as defineCustomElement$2 } from './pagination-menu2.js';

const makeGetPayments = ({ id, authToken, service }) => async ({ params, onSuccess, onError, final }) => {
    var _a, _b;
    try {
        const response = await service.fetchPayments(id, authToken, params);
        if (!response.error) {
            const pagingInfo = Object.assign({}, response.page_info);
            const payments = ((_a = response.data) === null || _a === void 0 ? void 0 : _a.map((dataItem) => new Payment(dataItem))) || [];
            onSuccess({ payments, pagingInfo });
        }
        else {
            const responseError = getErrorMessage(response.error);
            const code = getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error: responseError,
                code,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};

const mapCardBrandToDisplayName = (brand) => {
    if (!brand)
        return 'N/A';
    const brandMap = {
        'visa': 'VISA',
        'mastercard': 'Mastercard',
        'american_express': 'American Express',
        'discover': 'Discover',
        'diners_club': 'Diners Club',
        'jcb': 'JCB',
        'china_unionpay': 'China UnionPay',
        'unknown': 'Unknown'
    };
    return brandMap[brand.toLowerCase()] || brand;
};
const defaultColumnsKeys = 'created_at,amount,status,payment_type,description,payers_name,last_four_digits,card_brand';
const paymentTableColumns = {
    created_at: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time each payment was made" }, "Date")),
    amount: () => (h("th", { part: tableHeadCell, scope: "col", title: "The dollar amount of each payment" }, "Amount")),
    status: () => (h("th", { part: tableHeadCell, scope: "col", title: "The current status of each payment" }, "Status")),
    payment_type: () => (h("th", { part: tableHeadCell, scope: "col", title: "The type of each payment" }, "Type")),
    description: () => (h("th", { part: tableHeadCell, scope: "col", title: "The payment description, if you provided one" }, "Description")),
    payers_name: () => (h("th", { part: tableHeadCell, scope: "col", title: "The name associated with the payment method" }, "Account Holder")),
    last_four_digits: () => (h("th", { part: tableHeadCell, scope: "col", title: "The brand and last 4 digits of the payment method" }, "Payment Method")),
    card_brand: () => (h("th", { part: tableHeadCell, scope: "col", title: "The brand of the payment method" }, "Card Brand")),
};
const paymentTableCells = {
    created_at: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, h("div", { class: "fw-bold" }, convertToLocal(payment.created_at, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(payment.created_at, { showTime: true })))),
    amount: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, payment.formattedPaymentAmount(payment.amount))),
    status: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, MapPaymentStatusToBadge(payment.status))),
    payment_type: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, payment.payment_type)),
    description: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, payment.description)),
    payers_name: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, payment.payers_name)),
    last_four_digits: (payment, index) => (h("td", { part: getAlternateTableCellPart(index) }, payment.last_four_digits)),
    card_brand: (payment, index) => {
        var _a, _b;
        return (h("td", { part: getAlternateTableCellPart(index) }, mapCardBrandToDisplayName(((_a = payment.payment_method.card) === null || _a === void 0 ? void 0 : _a.brand) || ((_b = payment.payment_method.bank_account) === null || _b === void 0 ? void 0 : _b.brand))));
    },
};

const JustifiPaymentsList$1 = /*@__PURE__*/ proxyCustomElement(class JustifiPaymentsList extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.errorEvent = createEvent(this, "error-event", 7);
        this.clickEvent = createEvent(this, "click-event", 7);
        this.errorMessage = null;
        this.payments = [];
        this.loading = true;
        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 paymentData = this.payments.find((payment) => payment.id === clickedPaymentID);
            this.clickEvent.emit({ name: TableClickActions.row, data: paymentData });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.paymentsTable = new Table(this.payments, this.columns, paymentTableColumns, paymentTableCells);
        this.initializeGetPayments();
        onQueryParamsChange('set', () => {
            this.pagingParams = {};
            this.errorMessage = '';
        });
        onQueryParamsChange('reset', () => {
            this.pagingParams = {};
            this.errorMessage = '';
        });
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    ;
    propChanged() {
        this.initializeGetPayments();
    }
    updateOnPropChange() {
        this.fetchData();
    }
    initializeGetPayments() {
        if (this.accountId && this.authToken) {
            this.getPayments = makeGetPayments({
                id: this.accountId,
                authToken: this.authToken,
                service: new PaymentService()
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    fetchData() {
        if (!this.getPayments)
            return;
        this.loading = true;
        this.getPayments({
            params: this.paymentParams,
            onSuccess: ({ payments, pagingInfo }) => {
                this.payments = payments;
                this.paging = pagingInfo;
                this.paymentsTable.collectionData = this.payments;
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            },
            final: () => {
                this.loading = false;
            }
        });
    }
    get paymentParams() {
        const requestParams = getRequestParams();
        const params = Object.assign(Object.assign({}, requestParams), this.pagingParams);
        return params;
    }
    get entityId() {
        return this.payments.map((payment) => payment.id);
    }
    get showEmptyState() {
        return !this.loading && !this.errorMessage && this.paymentsTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.loading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.loading;
    }
    render() {
        return (h(StyledHost, { key: 'b2c7bd7573c3a2cdc683e6ea0b22bc625eaddbc6' }, h(TableWrapper, { key: 'edcc04c18ae762b75aab3cebe31a5aab824843ef' }, h(TableComponent, { key: '98b6e699948ac65667497b59b0ac23e36d7ea212' }, h(TableHead, { key: '06830e440c2f5ea23acd0109f58dd6e11f6495bf' }, h(TableHeadRow, { key: '8a29564e85eb5a870c37c58cc57a149327f5405d' }, this.paymentsTable.columnData.map((column) => column))), h(TableBody, { key: 'a03ffd7422fbf7f364a6f7545a0158fb0cd38691' }, h(TableLoadingState, { key: '6f48d9791c28a3407edddf97fc54a1a92c5e7dbc', columnSpan: this.paymentsTable.columnData.length, isLoading: this.loading }), h(TableEmptyState, { key: 'ab948e22cf74e5db93835df17f93c200f0caf698', isEmpty: this.showEmptyState, columnSpan: this.paymentsTable.columnData.length }), h(TableErrorState, { key: '28064e964a0db825ba7d78bc84e55c88b5c8e0c3', columnSpan: this.paymentsTable.columnData.length, errorMessage: this.errorMessage }), this.showRowData && this.paymentsTable.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: '036c71025fb6d150a3bdaa370e84e955ecf79b66' }, h(TableFootRow, { key: '373d7ac9f89a226a32a26a5ee7bb2a2246f8a454' }, h(TableFootCell, { key: 'a74ee4a4f5004dfe5e0513cfeea66c3b34b8d610', colSpan: this.paymentsTable.columnData.length }, h("pagination-menu", { key: '438d49d2094bb17488b8e2aa90fd0dbce100d920', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getPayments": ["updateOnPropChange"],
        "columns": ["updateOnPropChange"]
    }; }
}, [257, "justifi-payments-list", {
        "accountId": [1, "account-id"],
        "authToken": [1, "auth-token"],
        "columns": [1],
        "getPayments": [32],
        "errorMessage": [32],
        "payments": [32],
        "paymentsTable": [32],
        "loading": [32],
        "paging": [32],
        "pagingParams": [32]
    }, undefined, {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getPayments": ["updateOnPropChange"],
        "columns": ["updateOnPropChange"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-payments-list", "pagination-menu"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-payments-list":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiPaymentsList$1);
            }
            break;
        case "pagination-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiPaymentsList = JustifiPaymentsList$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiPaymentsList, defineCustomElement };
