import { h } from "@stencil/core";
import { PaymentService } from "../../api/services/payment.service";
import { makeGetPayments } from "../../actions/payment/get-payments";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../api/ComponentError";
import JustifiAnalytics from "../../api/Analytics";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import { StyledHost } from "../../ui-components";
import { paymentTableCells, paymentTableColumns } from "./payments-table";
import { defaultColumnsKeys } from "./payments-table";
import { pagingDefaults } from "../../api";
import { TableEmptyState, TableErrorState, TableLoadingState } from "../../ui-components";
import { Table } from "../../utils/table";
import { getRequestParams, onQueryParamsChange } from "./payments-list-params-state";
import { TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions } from "../../ui-components";
export class JustifiPaymentsList {
    constructor() {
        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 is() { return "justifi-payments-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"
            }
        };
    }
    static get states() {
        return {
            "getPayments": {},
            "errorMessage": {},
            "payments": {},
            "paymentsTable": {},
            "loading": {},
            "paging": {},
            "pagingParams": {}
        };
    }
    static get events() {
        return [{
                "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"
                        }
                    }
                }
            }, {
                "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"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "accountId",
                "methodName": "propChanged"
            }, {
                "propName": "authToken",
                "methodName": "propChanged"
            }, {
                "propName": "pagingParams",
                "methodName": "updateOnPropChange"
            }, {
                "propName": "getPayments",
                "methodName": "updateOnPropChange"
            }, {
                "propName": "columns",
                "methodName": "updateOnPropChange"
            }];
    }
}
