import { h } from "@stencil/core";
import { pagingDefaults } from "../../api";
import { makeGetCheckouts } from "../../actions/checkout/get-checkouts";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import JustifiAnalytics from "../../api/Analytics";
import { CheckoutService } from "../../api/services/checkout.service";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../api/ComponentError";
import { SubAccountService } from "../../api/services/subaccounts.service";
import { makeGetSubAccounts } from "../../actions/sub-account/get-subaccounts";
import { StyledHost, TableEmptyState, TableErrorState, TableLoadingState, TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions, } from "../../ui-components";
import { checkoutTableColumns, checkoutTableCells, defaultColumnsKeys } from "./checkouts-table";
import { Table } from "../../utils/table";
import { getRequestParams, onQueryParamsChange } from "./checkouts-list-params-state";
export class JustifiCheckoutsList {
    constructor() {
        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 is() { return "justifi-checkouts-list"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "accountId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "account-id"
            },
            "authToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "auth-token"
            },
            "columns": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "columns",
                "defaultValue": "defaultColumnsKeys"
            },
            "subAccountId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "sub-account-id"
            }
        };
    }
    static get states() {
        return {
            "checkouts": {},
            "checkoutsTable": {},
            "subAccounts": {},
            "loading": {},
            "errorMessage": {},
            "paging": {},
            "pagingParams": {},
            "getCheckouts": {},
            "getSubAccounts": {}
        };
    }
    static get events() {
        return [{
                "method": "clickEvent",
                "name": "click-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentClickEvent",
                    "resolved": "ComponentClickEvent",
                    "references": {
                        "ComponentClickEvent": {
                            "location": "import",
                            "path": "../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentClickEvent"
                        }
                    }
                }
            }, {
                "method": "errorEvent",
                "name": "error-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentErrorEvent",
                    "resolved": "ComponentErrorEvent",
                    "references": {
                        "ComponentErrorEvent": {
                            "location": "import",
                            "path": "../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentErrorEvent"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "accountId",
                "methodName": "authPropChanged"
            }, {
                "propName": "authToken",
                "methodName": "authPropChanged"
            }, {
                "propName": "subAccountId",
                "methodName": "authPropChanged"
            }, {
                "propName": "pagingParams",
                "methodName": "pagingOrColumnsChanged"
            }, {
                "propName": "columns",
                "methodName": "pagingOrColumnsChanged"
            }];
    }
}
