import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity, pagingDefaults } from "../../api";
import JustifiAnalytics from "../../api/Analytics";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import { makeGetPayoutTransactions } from "../../actions/payout/get-payout-transactions";
import { PayoutService } from "../../api/services/payout.service";
import { Table } from "../../utils/table";
import { StyledHost, TableEmptyState, TableErrorState, TableLoadingState } from "../../ui-components";
import { defaultColumnsKeys, payoutTransactionTableCells, payoutTransactionTableColumns } from "./payout-transactions-table";
import { configState } from "../config-provider/config-state";
import { TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions } from "../../ui-components";
export class JustifiPayoutTransactionsList {
    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 clickedPayoutId = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedPayoutId)
                return;
            const transactionData = this.balanceTransactions.find((payout) => payout.id === clickedPayoutId);
            this.clickEvent.emit({ name: TableClickActions.row, data: transactionData });
        };
    }
    componentWillLoad() {
        this.transactionsTable = new Table(this.balanceTransactions, this.columns, payoutTransactionTableColumns, payoutTransactionTableCells);
        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.payoutId && this.authToken) {
            const getPayoutTransactions = makeGetPayoutTransactions({
                accountId: configState.accountId,
                authToken: this.authToken,
                service: new PayoutService()
            });
            getPayoutTransactions({
                params: this.requestParams,
                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 = 'payout-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;
    }
    get requestParams() {
        return Object.assign({ payout_id: this.payoutId, limit: '15' }, this.pagingParams);
    }
    render() {
        return (h(StyledHost, { key: 'e7b5b219c34d1c8610fb4113fedd503f0512db2d' }, h(TableWrapper, { key: '97bbe678c90ba115a091db4fac42560c17f557f2' }, h(TableComponent, { key: 'ef90c77cd8f19a80e2b3e2b514aa1bc735a1b783' }, h(TableHead, { key: 'f5f0a00594f099931f1ac1cd4e359bb8fab11ec8' }, h(TableHeadRow, { key: '559648add19e0426d756f71ecb7bbd5cbcf1349e' }, this.transactionsTable.columnData.map((column) => column))), h(TableBody, { key: '49f8da0be5dba34ffbb92805d7b5b0fb3eeb6bf7' }, h(TableLoadingState, { key: '1d61dc2157608f38eb34e64452d7089857e6c67d', columnSpan: this.transactionsTable.columnKeys.length, isLoading: this.isLoading }), h(TableEmptyState, { key: 'd1f735fdb009740a186a16ea7e15d0320965a286', isEmpty: this.showEmptyState, columnSpan: this.transactionsTable.columnKeys.length }), h(TableErrorState, { key: 'f50ecc151be5c9143fb69d575a1ef14b3aa17b61', 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: '560536e623b2437d613169af2980aec13ebb4531' }, h(TableFootRow, { key: '42b82920fdd6056bb654db92acf3741aafb13d99' }, h(TableFootCell, { key: 'e2545104fdac51e0ada942138a08714f213bce63', colSpan: this.transactionsTable.columnData.length }, h("pagination-menu", { key: '6a74b19f3fa02f0e86e00783a06b0dfba2bc0ed8', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get is() { return "justifi-payout-transactions-list"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "payoutId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "payout-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": "payoutId",
                "methodName": "propChanged"
            }, {
                "propName": "authToken",
                "methodName": "propChanged"
            }];
    }
}
