import { h, r as registerInstance, c as createEvent } from './index-CV0Pyo1O.js';
import { k as Payout, C as ComponentErrorSeverity, b as ComponentErrorCodes } from './Plaid-DxSkT8pY.js';
import { J as JustifiAnalytics } from './Analytics-C76Y5Pqf.js';
import { c as checkPkgVersion } from './check-pkg-version-D5BxTNyL.js';
import { P as PayoutService } from './payout.service-yVnD7HWZ.js';
import './config-state-kKn89dp1.js';
import './dinero-HXpYMWUU.js';
import { p as pagingDefaults } from './Pagination-CLHwhyvu.js';
import './Business-BcNb9bVO.js';
import { g as getErrorCode, a as getErrorMessage } from './utils-CVYvs2hZ.js';
import { M as MapPayoutStatusToBadge, m as makeGetPayoutCSV } from './payouts-status-DoPgKv-W.js';
import { m as makeGetSubAccounts, S as SubAccountService } from './get-subaccounts-iBTEai_H.js';
import { S as StyledHost } from './styled-host-D84RBv1W.js';
import { T as Table, a as TableWrapper, b as TableComponent, c as TableHead, d as TableHeadRow, e as TableBody, f as TableLoadingState, g as TableEmptyState, h as TableErrorState, i as TableRow, j as TableFoot, k as TableFootRow, l as TableFootCell } from './table-DqGfsdys.js';
import { T as TableClickActions } from './event-types-CZfYo5-1.js';
import { a as convertToLocal } from './utils-C25uIOK0.js';
import { a6 as tableHeadCell, a7 as getAlternateTableCellPart } from './parts-CPKMvyV_.js';
import { o as onQueryParamsChange, g as getRequestParams } from './payouts-list-params-state-CiGfmyWW.js';
import './package-CqcLgdsl.js';
import './Api-BulOmiMS.js';
import './index-cDVGjRkU.js';
import './badge-Dlcl9qdm.js';
import './spinner-DIiQZd6_.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 Payout(dataItem))) || [];
            onSuccess({ payouts, pagingInfo });
        }
        else {
            const error = getErrorMessage(response.error);
            const code = getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error,
                code,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: ComponentErrorSeverity.ERROR,
        });
    }
};

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

const JustifiPayoutsList = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.clickEvent = createEvent(this, "click-event", 7);
        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 watchers() { return {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getPayouts": ["updateOnPropChange"],
        "getSubAccounts": ["updateOnPropChange"]
    }; }
};

export { JustifiPayoutsList as justifi_payouts_list };
