import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../api/ComponentError";
import JustifiAnalytics from "../../api/Analytics";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import { PayoutService } from "../../api/services/payout.service";
import { makeGetPayouts } from "../../actions/payout/get-payouts";
import { makeGetPayoutCSV } from "../payout-details/get-payout-csv";
import { SubAccountService } from "../../api/services/subaccounts.service";
import { StyledHost, TableEmptyState, TableErrorState, TableLoadingState } from "../../ui-components";
import { defaultColumnsKeys, payoutTableCells, payoutTableColumns } from "./payouts-table";
import { makeGetSubAccounts } from "../../actions/sub-account/get-subaccounts";
import { pagingDefaults } from "../../api";
import { Table } from "../../utils/table";
import { getRequestParams, onQueryParamsChange } from "./payouts-list-params-state";
import { TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions } from "../../ui-components";
export class JustifiPayoutsList {
    constructor() {
        this.errorMessage = null;
        this.payouts = [];
        this.subAccounts = [];
        this.loading = true;
        this.paging = pagingDefaults;
        this.pagingParams = {};
        this.columns = defaultColumnsKeys;
        this.downloadCSV = (payoutId) => {
            this.getPayoutCSV({
                payoutId,
                onError: () => {
                    this.errorEvent.emit({
                        errorCode: ComponentErrorCodes.FETCH_ERROR,
                        message: 'Failed to download CSV',
                        severity: ComponentErrorSeverity.ERROR,
                    });
                },
            });
        };
        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 clickedRow = e.target.closest('tr');
            const clickedPayoutID = clickedRow.dataset.rowEntityId;
            if (!clickedPayoutID)
                return;
            const clickedCSV = clickedRow.querySelector('a');
            if (clickedCSV === e.target)
                return;
            const payoutData = this.payouts.find((payout) => payout.id === clickedPayoutID);
            this.clickEvent.emit({ name: TableClickActions.row, data: payoutData });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.initializeGetData();
        this.payoutsTable = new Table(this.payouts, this.columns, payoutTableColumns, payoutTableCells(this.downloadCSV));
        if (this.getPayouts && this.getSubAccounts) {
            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();
    }
    ;
    propChanged() {
        this.initializeGetData();
    }
    updateOnPropChange() {
        this.fetchData();
    }
    initializeGetData() {
        this.initializePayoutsServices();
        this.initializeGetSubAccounts();
    }
    initializePayoutsServices() {
        if (this.accountId && this.authToken) {
            const serviceParams = {
                id: this.accountId,
                authToken: this.authToken,
                service: new PayoutService()
            };
            this.getPayouts = makeGetPayouts(serviceParams);
            this.getPayoutCSV = makeGetPayoutCSV(serviceParams);
        }
        else {
            this.errorMessage = '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() {
        this.loading = true;
        this.getPayouts({
            params: this.payoutParams,
            onSuccess: ({ payouts, pagingInfo }) => {
                this.payouts = payouts;
                this.paging = pagingInfo;
                this.payoutsTable.collectionData = this.payouts;
                const shouldFetchSubAccounts = this.payoutsTable.columnKeys.includes('sub_account_name');
                if (shouldFetchSubAccounts) {
                    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() {
        this.getSubAccounts({
            params: this.subAccountParams,
            onSuccess: ({ subAccounts }) => {
                this.subAccounts = subAccounts;
                this.payouts = this.payouts.map((payout) => {
                    var _a;
                    payout.sub_account_name = (_a = this.subAccounts.find((subAccount) => subAccount.id === payout.account_id)) === null || _a === void 0 ? void 0 : _a.name;
                    return payout;
                });
                this.loading = false;
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
                this.loading = false;
            },
        });
    }
    get payoutParams() {
        const requestParams = getRequestParams();
        const params = Object.assign(Object.assign({}, requestParams), this.pagingParams);
        return params;
    }
    get subAccountParams() {
        const accountIdNumbers = this.payouts.map((payout) => payout.account_id);
        const uniqueAccountIds = [...new Set(accountIdNumbers)];
        const accountIdString = uniqueAccountIds.join(',');
        return { sub_account_id: accountIdString };
    }
    get entityId() {
        return this.payouts.map((payout) => payout.id);
    }
    get showEmptyState() {
        return !this.loading && !this.errorMessage && this.payoutsTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.loading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.loading;
    }
    render() {
        return (h(StyledHost, { key: '653896fabc4becf531ec119d252cbaea301a0dc6' }, h(TableWrapper, { key: '63787473d67118a7f092bad666c47346872a7834' }, h(TableComponent, { key: 'c17ecce261475c8bfe357ff30d06f189c8f96480' }, h(TableHead, { key: 'cc23edeff6a1e595671b77fa51c73ff313692b16' }, h(TableHeadRow, { key: '4ed5b5ee149538d2de60ee6e27edde55e8d11eaa' }, this.payoutsTable.columnData.map((column) => column))), h(TableBody, { key: 'a0a886e70ba99ececd78e5bc34aec065466fe6ce' }, h(TableLoadingState, { key: '38bf9109ca73ecfd5c85529a8f7232069ffcdb00', columnSpan: this.payoutsTable.columnKeys.length, isLoading: this.loading }), h(TableEmptyState, { key: '6f5341305ef71f86bbf3680e2c6d0dc461f3d09f', isEmpty: this.showEmptyState, columnSpan: this.payoutsTable.columnKeys.length }), h(TableErrorState, { key: 'bd5e8cc72b460238636546a568645c797807f2d9', columnSpan: this.payoutsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.payoutsTable.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: '15145b7ef9cc37a2ad70cea5698d53df069979bf' }, h(TableFootRow, { key: '2d4ed5a1ab5eaf0eaae0bbe35f02edf59c23b22e' }, h(TableFootCell, { key: '11c8505cfd97117afaf79ea68a3fb00570a9c7cb', colSpan: this.payoutsTable.columnData.length }, h("pagination-menu", { key: 'b8e7e29d4d932f43b3381235de57b63cc6a5283b', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get is() { return "justifi-payouts-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 {
            "getPayouts": {},
            "getPayoutCSV": {},
            "getSubAccounts": {},
            "errorMessage": {},
            "payouts": {},
            "payoutsTable": {},
            "subAccounts": {},
            "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": "getPayouts",
                "methodName": "updateOnPropChange"
            }, {
                "propName": "getSubAccounts",
                "methodName": "updateOnPropChange"
            }];
    }
}
