import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity, pagingDefaults } from "../../api";
import JustifiAnalytics from "../../api/Analytics";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import { makeGetPaymentTransactions } from "../../actions/payment/get-payment-transactions";
import { PaymentService } from "../../api/services/payment.service";
import { Table } from "../../utils/table";
import { StyledHost, TableEmptyState, TableErrorState, TableLoadingState } from "../../ui-components";
import { defaultColumnsKeys, paymentTransactionTableCells, paymentTransactionTableColumns } from "./payment-transactions-table";
import { TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions } from "../../ui-components";
export class JustifiPaymentTransactionsList {
    constructor() {
        this.balanceTransactions = [];
        this.isLoading = true;
        this.errorMessage = null;
        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 transactionData = this.balanceTransactions.find((payment) => payment.id === clickedPaymentID);
            this.clickEvent.emit({ name: TableClickActions.row, data: transactionData });
        };
    }
    componentWillLoad() {
        this.transactionsTable = new Table(this.balanceTransactions, this.columns, paymentTransactionTableColumns, paymentTransactionTableCells);
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.initializeApi();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    ;
    propChanged() {
        this.initializeApi();
    }
    handleError(code, errorMessage, severity) {
        this.isLoading = false;
        this.errorEvent.emit({ errorCode: code, message: errorMessage, severity });
    }
    initializeApi() {
        if (this.paymentId && this.authToken) {
            const getPaymentTransactions = makeGetPaymentTransactions({
                id: this.paymentId,
                authToken: this.authToken,
                service: new PaymentService()
            });
            getPaymentTransactions({
                params: this.pagingParams,
                onSuccess: ({ balanceTransactions, pagingInfo }) => {
                    this.balanceTransactions = balanceTransactions;
                    this.paging = pagingInfo;
                    this.transactionsTable.collectionData = this.balanceTransactions;
                },
                onError: ({ error, code, severity }) => {
                    this.errorMessage = error.message;
                    this.handleError(error, code, severity);
                },
                final: () => {
                    this.isLoading = false;
                }
            });
        }
        else {
            this.errorMessage = 'payment-id and auth-token props are required';
            this.handleError(ComponentErrorCodes.MISSING_PROPS, this.errorMessage, ComponentErrorSeverity.ERROR);
        }
    }
    get entityId() {
        return this.balanceTransactions.map((transaction) => transaction.id);
    }
    get showEmptyState() {
        return !this.isLoading && !this.errorMessage && this.transactionsTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.isLoading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.isLoading;
    }
    render() {
        return (h(StyledHost, { key: '24e7a4313ab91f179fd27b6596f012487de06815' }, h(TableWrapper, { key: '1f9a7a56a940e41dd865bc6f3a8681ce86d60d58' }, h(TableComponent, { key: 'a26ce09ae4df84698be1ea37cb735e38c0a0402e' }, h(TableHead, { key: '07f8655efd483e1d9240e65b17dc13583028f376' }, h(TableHeadRow, { key: '0b62a7700715dbaffbedc0538432d075a3158499' }, this.transactionsTable.columnData.map((column) => column))), h(TableBody, { key: 'adf75fa50ddfb5257875b2779fc6c157812d4c19' }, h(TableLoadingState, { key: 'bc77de512b3e5fd1e6c4b8cf908b46027a3bc33f', columnSpan: this.transactionsTable.columnKeys.length, isLoading: this.isLoading }), h(TableEmptyState, { key: '413d46e184399cba3993f37efd64cb0d0a10d905', isEmpty: this.showEmptyState, columnSpan: this.transactionsTable.columnKeys.length }), h(TableErrorState, { key: '9deaa794dc848ed7c85cbadc3b4cfe7c9fb1176f', columnSpan: this.transactionsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.transactionsTable.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: '16ca0811bf42dc9419f8b77086e8e7e2cf6d0085' }, h(TableFootRow, { key: 'e11be42549832c35078acf47b7c165fe1e50ea98' }, h(TableFootCell, { key: '205d649068b84200b88adc1be9cfe192abfe13be', colSpan: this.transactionsTable.columnData.length }, h("pagination-menu", { key: '2a28645220d4f18b7037e461bd93eefc3aed49a0', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get is() { return "justifi-payment-transactions-list"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "paymentId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "payment-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 {
            "balanceTransactions": {},
            "transactionsTable": {},
            "isLoading": {},
            "errorMessage": {},
            "paging": {},
            "pagingParams": {}
        };
    }
    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",
                            "id": "src/api/index.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",
                            "id": "src/api/index.ts::ComponentErrorEvent"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "pagingParams",
                "methodName": "propChanged"
            }, {
                "propName": "paymentId",
                "methodName": "propChanged"
            }, {
                "propName": "authToken",
                "methodName": "propChanged"
            }];
    }
}
