'use strict';

var index = require('./index-p7cvUYAE.js');
var payment_service = require('./payment.service-8Q-EEtXL.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 utils = require('./utils-BsnepLy6.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
var table = require('./table-DjbNv28p.js');
var eventTypes = require('./event-types-YOY5TKUN.js');
var paymentsStatus = require('./payments-status-Bj_bCKUP.js');
var utils$1 = require('./utils-CYONRFR6.js');
var parts = require('./parts-BXshb_S-.js');
var paymentsListParamsState = require('./payments-list-params-state-vGJZ6Oe2.js');
require('./Api-D9vOcUw4.js');
require('./index-W-zoNiyM.js');
require('./package-YyJzVqrh.js');
require('./spinner-C6ZGOB2P.js');
require('./badge-GBNtUypt.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 Plaid.Payment(dataItem))) || [];
            onSuccess({ payments, pagingInfo });
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.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: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The date and time each payment was made" }, "Date")),
    amount: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The dollar amount of each payment" }, "Amount")),
    status: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The current status of each payment" }, "Status")),
    payment_type: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The type of each payment" }, "Type")),
    description: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The payment description, if you provided one" }, "Description")),
    payers_name: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The name associated with the payment method" }, "Account Holder")),
    last_four_digits: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The brand and last 4 digits of the payment method" }, "Payment Method")),
    card_brand: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The brand of the payment method" }, "Card Brand")),
};
const paymentTableCells = {
    created_at: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("div", { class: "fw-bold" }, utils$1.convertToLocal(payment.created_at, { showDisplayDate: true })), index.h("div", { class: "fw-bold" }, utils$1.convertToLocal(payment.created_at, { showTime: true })))),
    amount: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payment.formattedPaymentAmount(payment.amount))),
    status: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, paymentsStatus.MapPaymentStatusToBadge(payment.status))),
    payment_type: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payment.payment_type)),
    description: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payment.description)),
    payers_name: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payment.payers_name)),
    last_four_digits: (payment, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payment.last_four_digits)),
    card_brand: (payment, index$1) => {
        var _a, _b;
        return (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, 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 = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorMessage = null;
        this.payments = [];
        this.loading = true;
        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 paymentData = this.payments.find((payment) => payment.id === clickedPaymentID);
            this.clickEvent.emit({ name: eventTypes.TableClickActions.row, data: paymentData });
        };
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.paymentsTable = new table.Table(this.payments, this.columns, paymentTableColumns, paymentTableCells);
        this.initializeGetPayments();
        paymentsListParamsState.onQueryParamsChange('set', () => {
            this.pagingParams = {};
            this.errorMessage = '';
        });
        paymentsListParamsState.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 payment_service.PaymentService()
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: Plaid.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 = paymentsListParamsState.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 (index.h(styledHost.StyledHost, { key: 'b2c7bd7573c3a2cdc683e6ea0b22bc625eaddbc6' }, index.h(table.TableWrapper, { key: 'edcc04c18ae762b75aab3cebe31a5aab824843ef' }, index.h(table.TableComponent, { key: '98b6e699948ac65667497b59b0ac23e36d7ea212' }, index.h(table.TableHead, { key: '06830e440c2f5ea23acd0109f58dd6e11f6495bf' }, index.h(table.TableHeadRow, { key: '8a29564e85eb5a870c37c58cc57a149327f5405d' }, this.paymentsTable.columnData.map((column) => column))), index.h(table.TableBody, { key: 'a03ffd7422fbf7f364a6f7545a0158fb0cd38691' }, index.h(table.TableLoadingState, { key: '6f48d9791c28a3407edddf97fc54a1a92c5e7dbc', columnSpan: this.paymentsTable.columnData.length, isLoading: this.loading }), index.h(table.TableEmptyState, { key: 'ab948e22cf74e5db93835df17f93c200f0caf698', isEmpty: this.showEmptyState, columnSpan: this.paymentsTable.columnData.length }), index.h(table.TableErrorState, { key: '28064e964a0db825ba7d78bc84e55c88b5c8e0c3', columnSpan: this.paymentsTable.columnData.length, errorMessage: this.errorMessage }), this.showRowData && this.paymentsTable.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: '036c71025fb6d150a3bdaa370e84e955ecf79b66' }, index.h(table.TableFootRow, { key: '373d7ac9f89a226a32a26a5ee7bb2a2246f8a454' }, index.h(table.TableFootCell, { key: 'a74ee4a4f5004dfe5e0513cfeea66c3b34b8d610', colSpan: this.paymentsTable.columnData.length }, index.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"]
    }; }
};

exports.justifi_payments_list = JustifiPaymentsList;
