'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 utils = require('./utils-BsnepLy6.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var checkout_service = require('./checkout.service-Bc6RAR8j.js');
var getSubaccounts = require('./get-subaccounts-srp4S2Um.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
var table = require('./table-DjbNv28p.js');
var eventTypes = require('./event-types-YOY5TKUN.js');
var utils$1 = require('./utils-CYONRFR6.js');
var badge = require('./badge-GBNtUypt.js');
var parts = require('./parts-BXshb_S-.js');
var checkoutsListParamsState = require('./checkouts-list-params-state-vGJZ6Oe2.js');
require('./index-W-zoNiyM.js');
require('./package-YyJzVqrh.js');
require('./Api-D9vOcUw4.js');
require('./spinner-C6ZGOB2P.js');

const makeGetCheckouts = ({ accountId, authToken, service }) => async ({ params, onSuccess, onError }) => {
    var _a, _b;
    try {
        const response = await service.fetchCheckouts(accountId, authToken, params);
        if (!response.error) {
            const pagingInfo = Object.assign({}, response.page_info);
            const checkouts = ((_a = response.data) === null || _a === void 0 ? void 0 : _a.map((dataItem) => new Plaid.Checkout(dataItem))) || [];
            onSuccess({ checkouts, 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,
        });
    }
};

const MapCheckoutStatusToBadge = (status) => {
    const statusToBadgeProps = {
        created: {
            variant: badge.BadgeVariant.PRIMARY,
            title: 'The checkout has been created',
            text: 'Created',
        },
        completed: {
            variant: badge.BadgeVariant.SUCCESS,
            title: 'The checkout has been completed',
            text: 'Completed',
        },
        attempted: {
            variant: badge.BadgeVariant.SECONDARY,
            title: 'The checkout has been attempted',
            text: 'Attempted',
        },
        expired: {
            variant: badge.BadgeVariant.DANGER,
            title: 'The checkout has expired',
            text: 'Expired',
        },
    };
    const badgeProps = statusToBadgeProps[status];
    return index.h(badge.Badge, Object.assign({}, badgeProps));
};

const defaultColumnsKeys = 'created_at,payment_amount,payment_description,payment_mode,status';
const checkoutTableColumns = {
    created_at: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The date each checkout occurred" }, "Processed On")),
    payment_amount: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The dollar amount of each checkout" }, "Payment Amount")),
    payment_description: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The description of each checkout" }, "Payment Description")),
    sub_account_name: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The sub account associated with the checkout" }, "Sub Account")),
    payment_mode: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The payment mode of each checkout" }, "Payment Mode")),
    status: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The current status of each checkout" }, "Status")),
};
const checkoutTableCells = {
    created_at: (checkout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("div", { class: "fw-bold" }, utils$1.formatDate(checkout.created_at)), index.h("div", { class: "fw-bold" }, utils$1.formatTime(checkout.created_at)))),
    payment_amount: (checkout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, checkout.formattedPaymentAmount(checkout.payment_amount))),
    payment_description: (checkout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, checkout.payment_description)),
    sub_account_name: (checkout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, checkout.sub_account_name)),
    payment_mode: (checkout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, checkout.payment_mode)),
    status: (checkout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, MapCheckoutStatusToBadge(checkout.status))),
};

const JustifiCheckoutsList = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.columns = defaultColumnsKeys;
        this.checkouts = [];
        this.subAccounts = [];
        this.loading = true;
        this.paging = Pagination.pagingDefaults;
        this.pagingParams = {};
        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 clickedCheckoutID = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedCheckoutID)
                return;
            const checkoutData = this.checkouts.find((checkout) => checkout.id === clickedCheckoutID);
            this.clickEvent.emit({ name: eventTypes.TableClickActions.row, data: checkoutData });
        };
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.checkoutsTable = new table.Table(this.checkouts, this.columns, checkoutTableColumns, checkoutTableCells);
        this.initializeGetData();
        if (this.getCheckouts) {
            this.fetchData();
        }
        checkoutsListParamsState.onQueryParamsChange('set', () => {
            this.pagingParams = {};
        });
        checkoutsListParamsState.onQueryParamsChange('reset', () => {
            this.pagingParams = {};
            this.errorMessage = '';
        });
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    authPropChanged() {
        this.initializeGetData();
        if (this.getCheckouts) {
            this.fetchData();
        }
    }
    pagingOrColumnsChanged() {
        if (this.getCheckouts) {
            this.fetchData();
        }
    }
    initializeGetData() {
        this.initializeGetCheckouts();
        this.initializeGetSubAccounts();
    }
    initializeGetCheckouts() {
        const accountToUse = this.subAccountId || this.accountId;
        if (accountToUse && this.authToken) {
            this.getCheckouts = makeGetCheckouts({
                accountId: accountToUse,
                authToken: this.authToken,
                service: new checkout_service.CheckoutService(),
            });
        }
        else {
            this.errorMessage = 'Account ID/Sub Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    initializeGetSubAccounts() {
        if (this.accountId && this.authToken) {
            this.getSubAccounts = getSubaccounts.makeGetSubAccounts({
                primaryAccountId: this.accountId,
                authToken: this.authToken,
                service: new getSubaccounts.SubAccountService(),
            });
        }
    }
    fetchData() {
        if (!this.getCheckouts) {
            return;
        }
        this.loading = true;
        this.getCheckouts({
            params: this.checkoutParams,
            onSuccess: async ({ checkouts, pagingInfo }) => {
                this.checkouts = checkouts;
                this.paging = pagingInfo;
                this.checkoutsTable.collectionData = this.checkouts;
                const shouldFetchSubAccounts = this.checkoutsTable.columnKeys.includes('sub_account_name');
                if (shouldFetchSubAccounts) {
                    await this.fetchSubAccounts();
                }
                else {
                    this.loading = false;
                }
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
                this.loading = false;
            },
        });
    }
    async fetchSubAccounts() {
        if (!this.getSubAccounts) {
            this.loading = false;
            return;
        }
        this.getSubAccounts({
            params: this.subAccountParams,
            onSuccess: ({ subAccounts }) => {
                this.subAccounts = subAccounts;
                this.checkouts = this.checkouts.map((checkout) => {
                    var _a;
                    checkout.sub_account_name = (_a = this.subAccounts.find((subAccount) => subAccount.id === checkout.account_id)) === null || _a === void 0 ? void 0 : _a.name;
                    return checkout;
                });
                this.loading = false;
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
                this.loading = false;
            },
        });
    }
    get checkoutParams() {
        const requestParams = checkoutsListParamsState.getRequestParams();
        const params = Object.assign(Object.assign({}, requestParams), this.pagingParams);
        return params;
    }
    get subAccountParams() {
        const accountIdNumbers = this.checkouts.map((checkout) => checkout.account_id);
        const uniqueAccountIds = [...new Set(accountIdNumbers)];
        const accountIdString = uniqueAccountIds.join(',');
        return { sub_account_id: accountIdString };
    }
    get entityId() {
        return this.checkouts.map((checkout) => checkout.id);
    }
    get showEmptyState() {
        return !this.loading && !this.errorMessage && this.checkoutsTable.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: 'd384dda32587dfc469e998b2b8f209ef17aef775' }, index.h(table.TableWrapper, { key: '98f2472188e64a236fd5cc581efe2895a6de58a3' }, index.h(table.TableComponent, { key: 'f02db4d024b9d2250a637fb28dca06eaff1d894c' }, index.h(table.TableHead, { key: '8c96bfa14e4e2154c1f575595f9597d3adc640df' }, index.h(table.TableHeadRow, { key: '08cddf6a31fbe99c8b46f61ceca996acb9b87f0b' }, this.checkoutsTable.columnData.map((column) => column))), index.h(table.TableBody, { key: '99b88bfdb3871f82d653b00536f22c5c17cf38ac' }, index.h(table.TableLoadingState, { key: 'e05e1d543481df360b42e5563d5963277d10110e', columnSpan: this.checkoutsTable.columnKeys.length, isLoading: this.loading }), index.h(table.TableEmptyState, { key: '3c4e19d3e8c9c779249efa63be592fbf5948b6ae', isEmpty: this.showEmptyState, columnSpan: this.checkoutsTable.columnKeys.length }), index.h(table.TableErrorState, { key: '7660b4991974dc46d8fb9dfd28ef7ea79d8e22e0', columnSpan: this.checkoutsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData &&
            this.checkoutsTable.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: 'd56c6cb6a529dabf00c5260a39a2e2ab8e3749be' }, index.h(table.TableFootRow, { key: 'd28363ad8d8823f3da097edb263aa10308cbdb04' }, index.h(table.TableFootCell, { key: 'd6fcce3cf39e43718e8b15d42445c053d0feaa21', colSpan: this.checkoutsTable.columnData.length }, index.h("pagination-menu", { key: '6b956571ed6ae297df5430cad4be92eee2bdb9cc', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "accountId": ["authPropChanged"],
        "authToken": ["authPropChanged"],
        "subAccountId": ["authPropChanged"],
        "pagingParams": ["pagingOrColumnsChanged"],
        "columns": ["pagingOrColumnsChanged"]
    }; }
};

exports.justifi_checkouts_list = JustifiCheckoutsList;
