import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import './config-state.js';
import './dinero.js';
import { q as Checkout, 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 { c as checkPkgVersion } from './check-pkg-version.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { C as CheckoutService } from './checkout.service.js';
import { m as makeGetSubAccounts, S as SubAccountService } from './get-subaccounts.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 { f as formatDate, a as formatTime } from './utils2.js';
import { B as Badge, a as BadgeVariant } from './badge.js';
import { D as tableHeadCell, ah as getAlternateTableCellPart } from './parts.js';
import { o as onQueryParamsChange, g as getRequestParams } from './checkouts-list-params-state.js';
import { d as defineCustomElement$2 } from './pagination-menu2.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 Checkout(dataItem))) || [];
            onSuccess({ checkouts, 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,
        });
    }
};

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

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

const JustifiCheckoutsList$1 = /*@__PURE__*/ proxyCustomElement(class JustifiCheckoutsList 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.columns = defaultColumnsKeys;
        this.checkouts = [];
        this.subAccounts = [];
        this.loading = true;
        this.paging = pagingDefaults;
        this.pagingParams = {};
        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 clickedCheckoutID = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedCheckoutID)
                return;
            const checkoutData = this.checkouts.find((checkout) => checkout.id === clickedCheckoutID);
            this.clickEvent.emit({ name: TableClickActions.row, data: checkoutData });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.checkoutsTable = new Table(this.checkouts, this.columns, checkoutTableColumns, checkoutTableCells);
        this.initializeGetData();
        if (this.getCheckouts) {
            this.fetchData();
        }
        onQueryParamsChange('set', () => {
            this.pagingParams = {};
        });
        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 CheckoutService(),
            });
        }
        else {
            this.errorMessage = 'Account ID/Sub Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    initializeGetSubAccounts() {
        if (this.accountId && this.authToken) {
            this.getSubAccounts = makeGetSubAccounts({
                primaryAccountId: this.accountId,
                authToken: this.authToken,
                service: new 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 = 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 (h(StyledHost, { key: 'd384dda32587dfc469e998b2b8f209ef17aef775' }, h(TableWrapper, { key: '98f2472188e64a236fd5cc581efe2895a6de58a3' }, h(TableComponent, { key: 'f02db4d024b9d2250a637fb28dca06eaff1d894c' }, h(TableHead, { key: '8c96bfa14e4e2154c1f575595f9597d3adc640df' }, h(TableHeadRow, { key: '08cddf6a31fbe99c8b46f61ceca996acb9b87f0b' }, this.checkoutsTable.columnData.map((column) => column))), h(TableBody, { key: '99b88bfdb3871f82d653b00536f22c5c17cf38ac' }, h(TableLoadingState, { key: 'e05e1d543481df360b42e5563d5963277d10110e', columnSpan: this.checkoutsTable.columnKeys.length, isLoading: this.loading }), h(TableEmptyState, { key: '3c4e19d3e8c9c779249efa63be592fbf5948b6ae', isEmpty: this.showEmptyState, columnSpan: this.checkoutsTable.columnKeys.length }), h(TableErrorState, { key: '7660b4991974dc46d8fb9dfd28ef7ea79d8e22e0', columnSpan: this.checkoutsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData &&
            this.checkoutsTable.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: 'd56c6cb6a529dabf00c5260a39a2e2ab8e3749be' }, h(TableFootRow, { key: 'd28363ad8d8823f3da097edb263aa10308cbdb04' }, h(TableFootCell, { key: 'd6fcce3cf39e43718e8b15d42445c053d0feaa21', colSpan: this.checkoutsTable.columnData.length }, 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"]
    }; }
}, [257, "justifi-checkouts-list", {
        "accountId": [1, "account-id"],
        "authToken": [1, "auth-token"],
        "columns": [1],
        "subAccountId": [1, "sub-account-id"],
        "checkouts": [32],
        "checkoutsTable": [32],
        "subAccounts": [32],
        "loading": [32],
        "errorMessage": [32],
        "paging": [32],
        "pagingParams": [32],
        "getCheckouts": [32],
        "getSubAccounts": [32]
    }, undefined, {
        "accountId": ["authPropChanged"],
        "authToken": ["authPropChanged"],
        "subAccountId": ["authPropChanged"],
        "pagingParams": ["pagingOrColumnsChanged"],
        "columns": ["pagingOrColumnsChanged"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-checkouts-list", "pagination-menu"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-checkouts-list":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiCheckoutsList$1);
            }
            break;
        case "pagination-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiCheckoutsList = JustifiCheckoutsList$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiCheckoutsList, defineCustomElement };
