'use strict';

var index = require('./index-p7cvUYAE.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var payout_service = require('./payout.service-B6j2g-G5.js');
require('./config-state-BIgGhhe9.js');
require('./dinero-BwNN_k7x.js');
var Pagination = require('./Pagination-Dediz133.js');
require('./Business-oBifyXkW.js');
var utils = require('./utils-BsnepLy6.js');
var payoutsStatus = require('./payouts-status-C2KFg1AD.js');
var getSubaccounts = require('./get-subaccounts-srp4S2Um.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
var table = require('./table-DjbNv28p.js');
var eventTypes = require('./event-types-YOY5TKUN.js');
var utils$1 = require('./utils-CYONRFR6.js');
var parts = require('./parts-BXshb_S-.js');
var payoutsListParamsState = require('./payouts-list-params-state-vGJZ6Oe2.js');
require('./package-YyJzVqrh.js');
require('./Api-D9vOcUw4.js');
require('./index-W-zoNiyM.js');
require('./badge-GBNtUypt.js');
require('./spinner-C6ZGOB2P.js');

const makeGetPayouts = ({ id, authToken, service }) => async ({ params, onSuccess, onError }) => {
    var _a, _b;
    try {
        const response = await service.fetchPayouts(id, authToken, params);
        if (!response.error) {
            const pagingInfo = Object.assign({}, response.page_info);
            const payouts = ((_a = response.data) === null || _a === void 0 ? void 0 : _a.map((dataItem) => new Plaid.Payout(dataItem))) || [];
            onSuccess({ payouts, pagingInfo });
        }
        else {
            const error = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
};

const defaultColumnsKeys = 'created_at,amount,status,payments_total,refunds_total,fees_total,other_total,csv';
const payoutTableColumns = {
    created_at: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The date the payout was deposited" }, "Created")),
    sub_account_name: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The sub account associated with the payout" }, "Sub Account")),
    payments_total: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The total payments amount associated with the payout" }, "Payments")),
    refunds_total: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The total refunds amount associated with the payout" }, "Refunds")),
    fees_total: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The total fees amount associated with the payout" }, "Fees")),
    other_total: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The total other amount" }, "Other")),
    amount: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The total amount of the payout" }, "Amount")),
    status: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The real-time status of each payout" }, "Status")),
    csv: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "Export CSV" })),
};
const payoutTableCells = (downloadCSV) => ({
    created_at: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("div", { class: "fw-bold" }, utils$1.convertToLocal(payout.created_at, { showDisplayDate: true })))),
    sub_account_name: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payout.sub_account_name)),
    payments_total: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payout.formattedPaymentAmount(payout.payments_total))),
    refunds_total: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payout.formattedPaymentAmount(payout.refunds_total))),
    fees_total: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payout.formattedPaymentAmount(payout.fees_total))),
    other_total: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payout.formattedPaymentAmount(payout.other_total))),
    amount: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payout.formattedPaymentAmount(payout.amount))),
    status: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, payoutsStatus.MapPayoutStatusToBadge(payout.status))),
    csv: (payout, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("a", { href: "#", onClick: (event) => { event.preventDefault(); downloadCSV(payout.id); } }, "CSV"))),
});

const JustifiPayoutsList = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorMessage = null;
        this.payouts = [];
        this.subAccounts = [];
        this.loading = true;
        this.paging = Pagination.pagingDefaults;
        this.pagingParams = {};
        this.columns = defaultColumnsKeys;
        this.downloadCSV = (payoutId) => {
            this.getPayoutCSV({
                payoutId,
                onError: () => {
                    this.errorEvent.emit({
                        errorCode: Plaid.ComponentErrorCodes.FETCH_ERROR,
                        message: 'Failed to download CSV',
                        severity: Plaid.ComponentErrorSeverity.ERROR,
                    });
                },
            });
        };
        this.handleClickPrevious = (beforeCursor) => {
            this.pagingParams = { before_cursor: beforeCursor };
            this.clickEvent.emit({ name: eventTypes.TableClickActions.previous });
        };
        this.handleClickNext = (afterCursor) => {
            this.pagingParams = { after_cursor: afterCursor };
            this.clickEvent.emit({ name: eventTypes.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: eventTypes.TableClickActions.row, data: payoutData });
        };
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.initializeGetData();
        this.payoutsTable = new table.Table(this.payouts, this.columns, payoutTableColumns, payoutTableCells(this.downloadCSV));
        if (this.getPayouts && this.getSubAccounts) {
            this.fetchData();
        }
        payoutsListParamsState.onQueryParamsChange('set', () => {
            this.pagingParams = {};
        });
        payoutsListParamsState.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 payout_service.PayoutService()
            };
            this.getPayouts = makeGetPayouts(serviceParams);
            this.getPayoutCSV = payoutsStatus.makeGetPayoutCSV(serviceParams);
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    initializeGetSubAccounts() {
        if (this.accountId && this.authToken) {
            this.getSubAccounts = getSubaccounts.makeGetSubAccounts({
                primaryAccountId: this.accountId,
                authToken: this.authToken,
                service: new getSubaccounts.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 = payoutsListParamsState.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 (index.h(styledHost.StyledHost, { key: '653896fabc4becf531ec119d252cbaea301a0dc6' }, index.h(table.TableWrapper, { key: '63787473d67118a7f092bad666c47346872a7834' }, index.h(table.TableComponent, { key: 'c17ecce261475c8bfe357ff30d06f189c8f96480' }, index.h(table.TableHead, { key: 'cc23edeff6a1e595671b77fa51c73ff313692b16' }, index.h(table.TableHeadRow, { key: '4ed5b5ee149538d2de60ee6e27edde55e8d11eaa' }, this.payoutsTable.columnData.map((column) => column))), index.h(table.TableBody, { key: 'a0a886e70ba99ececd78e5bc34aec065466fe6ce' }, index.h(table.TableLoadingState, { key: '38bf9109ca73ecfd5c85529a8f7232069ffcdb00', columnSpan: this.payoutsTable.columnKeys.length, isLoading: this.loading }), index.h(table.TableEmptyState, { key: '6f5341305ef71f86bbf3680e2c6d0dc461f3d09f', isEmpty: this.showEmptyState, columnSpan: this.payoutsTable.columnKeys.length }), index.h(table.TableErrorState, { key: 'bd5e8cc72b460238636546a568645c797807f2d9', columnSpan: this.payoutsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.payoutsTable.rowData.map((data, index$1) => (index.h(table.TableRow, { "data-test-id": "table-row", "data-row-entity-id": this.entityId[index$1], onClick: this.rowClickHandler }, data)))), this.paging && (index.h(table.TableFoot, { key: '15145b7ef9cc37a2ad70cea5698d53df069979bf' }, index.h(table.TableFootRow, { key: '2d4ed5a1ab5eaf0eaae0bbe35f02edf59c23b22e' }, index.h(table.TableFootCell, { key: '11c8505cfd97117afaf79ea68a3fb00570a9c7cb', colSpan: this.payoutsTable.columnData.length }, index.h("pagination-menu", { key: 'b8e7e29d4d932f43b3381235de57b63cc6a5283b', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getPayouts": ["updateOnPropChange"],
        "getSubAccounts": ["updateOnPropChange"]
    }; }
};

exports.justifi_payouts_list = JustifiPayoutsList;
