import { h, r as registerInstance, c as createEvent } from './index-CV0Pyo1O.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 { c as checkPkgVersion } from './check-pkg-version-D5BxTNyL.js';
import { a6 as tableHeadCell, a7 as getAlternateTableCellPart } from './parts-CPKMvyV_.js';
import { a as convertToLocal } from './utils-C25uIOK0.js';
import './config-state-kKn89dp1.js';
import { f as TerminalOrderType, p as TerminalOrder, C as ComponentErrorSeverity, b as ComponentErrorCodes } from './Plaid-DxSkT8pY.js';
import { p as pagingDefaults } from './Pagination-CLHwhyvu.js';
import './Business-BcNb9bVO.js';
import { B as BadgeVariant, a as Badge } from './badge-Dlcl9qdm.js';
import './dinero-HXpYMWUU.js';
import { g as getErrorCode, a as getErrorMessage } from './utils-CVYvs2hZ.js';
import { A as Api } from './Api-BulOmiMS.js';
import { J as JustifiAnalytics } from './Analytics-C76Y5Pqf.js';
import { o as onQueryParamsChange, g as getRequestParams } from './terminal-orders-list-params-state-CiGfmyWW.js';
import './spinner-DIiQZd6_.js';
import './package-CqcLgdsl.js';
import './index-cDVGjRkU.js';

const MapTerminalOrderStatusToBadge = (status) => {
    const statusToBadgeProps = {
        submitted: {
            variant: BadgeVariant.PRIMARY,
            title: 'This order is submitted',
            text: 'Submitted',
        },
        completed: {
            variant: BadgeVariant.SUCCESS,
            title: 'This order has been completed',
            text: 'Completed',
        },
        created: {
            variant: BadgeVariant.SECONDARY,
            title: 'This order is created',
            text: 'Created',
        },
        in_progress: {
            variant: BadgeVariant.PRIMARY,
            title: 'This order is in progress',
            text: 'In Progress',
        },
        on_hold: {
            variant: BadgeVariant.WARNING,
            title: 'This order is on hold',
            text: 'On Hold',
        },
        canceled: {
            variant: BadgeVariant.DANGER,
            title: 'This order is canceled',
            text: 'Canceled',
        }
    };
    const badgeProps = statusToBadgeProps[status];
    return h(Badge, Object.assign({}, badgeProps));
};

const defaultColumnsKeys = 'created_at,updated_at,order_status,quantity';
const terminalOrdersTableColumns = {
    created_at: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time the order was created" }, "Created At")),
    updated_at: () => (h("th", { part: tableHeadCell, scope: "col", title: "The date and time the order was last updated" }, "Updated At")),
    order_status: () => (h("th", { part: tableHeadCell, scope: "col", title: "The current status of the order" }, "Order Status")),
    business_id: () => (h("th", { part: tableHeadCell, scope: "col", title: "The business ID associated with the order" }, "Business ID")),
    company_name: () => (h("th", { part: tableHeadCell, scope: "col", title: "The business name associated with the order" }, "Business Name")),
    provider: () => (h("th", { part: tableHeadCell, scope: "col", title: "The provider associated with the order" }, "Provider")),
    order_type: () => (h("th", { part: tableHeadCell, scope: "col", title: "The type of order" }, "Order Type")),
    quantity: () => (h("th", { part: tableHeadCell, scope: "col", title: "The number of terminals associated with the order" }, "Order Quantity")),
};
const terminalOrdersTableCells = {
    created_at: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, h("div", { class: "fw-bold" }, convertToLocal(terminalOrder.created_at, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(terminalOrder.created_at, { showTime: true })))),
    updated_at: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, h("div", { class: "fw-bold" }, convertToLocal(terminalOrder.updated_at, { showDisplayDate: true })), h("div", { class: "fw-bold" }, convertToLocal(terminalOrder.updated_at, { showTime: true })))),
    order_status: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, MapTerminalOrderStatusToBadge(terminalOrder.order_status))),
    business_id: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, terminalOrder.business_id)),
    company_name: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, terminalOrder.company_name)),
    provider: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, terminalOrder.provider)),
    order_type: (terminalOrder, index) => {
        let orderType;
        if (terminalOrder.order_type === TerminalOrderType.boardingOnly) {
            orderType = 'Boarding Only';
        }
        else if (terminalOrder.order_type === TerminalOrderType.boardingShipping) {
            orderType = 'Boarding & Shipping';
        }
        return (h("td", { part: getAlternateTableCellPart(index) }, orderType));
    },
    quantity: (terminalOrder, index) => (h("td", { part: getAlternateTableCellPart(index) }, terminalOrder.terminals.length)),
};

const makeGetTerminalOrders = ({ id, authToken, service }) => async ({ params, onSuccess, onError, final }) => {
    var _a, _b;
    try {
        const response = await service.fetchTerminalOrders(id, authToken, params);
        if (!response.error) {
            const pagingInfo = Object.assign({}, response.page_info);
            const terminalOrders = ((_a = response.data) === null || _a === void 0 ? void 0 : _a.map((dataItem) => new TerminalOrder(dataItem))) || [];
            onSuccess({ terminalOrders, pagingInfo });
        }
        else {
            const responseError = getErrorMessage(response.error);
            const code = getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error: responseError,
                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,
        });
    }
    finally {
        final();
    }
};

const api = Api();
class TerminalOrderService {
    async fetchTerminalOrders(accountId, authToken, params) {
        const endpoint = 'terminals/orders';
        const headers = { account: accountId };
        return api.get({ endpoint, params, headers, authToken });
    }
}

const JustifiTerminalOrdersList = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.clickEvent = createEvent(this, "click-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.columns = defaultColumnsKeys;
        this.terminalOrders = [];
        this.loading = true;
        this.paging = pagingDefaults;
        this.pagingParams = {};
        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 clickedOrderId = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedOrderId)
                return;
            const orderData = this.terminalOrders.find((order) => order.id === clickedOrderId);
            this.clickEvent.emit({ name: TableClickActions.row, data: orderData });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.terminalOrdersTable = new Table(this.terminalOrders, this.columns, terminalOrdersTableColumns, terminalOrdersTableCells);
        this.initializeGetData();
        if (this.getTerminalOrders) {
            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();
    }
    authPropChanged() {
        this.initializeGetData();
        if (this.getTerminalOrders) {
            this.fetchData();
        }
    }
    pagingOrColumnsChanged() {
        if (this.getTerminalOrders) {
            this.fetchData();
        }
    }
    initializeGetData() {
        if (this.accountId && this.authToken) {
            this.getTerminalOrders = makeGetTerminalOrders({
                id: this.accountId,
                authToken: this.authToken,
                service: new TerminalOrderService(),
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    fetchData() {
        if (!this.getTerminalOrders) {
            return;
        }
        this.loading = true;
        this.getTerminalOrders({
            params: this.terminalOrderParams,
            onSuccess: async ({ terminalOrders, pagingInfo }) => {
                this.terminalOrders = terminalOrders;
                this.paging = pagingInfo;
                this.terminalOrdersTable.collectionData = this.terminalOrders;
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            },
            final: () => {
                this.loading = false;
            },
        });
    }
    get terminalOrderParams() {
        const requestParams = getRequestParams();
        const params = Object.assign(Object.assign({}, requestParams), this.pagingParams);
        return params;
    }
    get entityId() {
        return this.terminalOrders.map((terminalOrder) => terminalOrder.id);
    }
    get showEmptyState() {
        return !this.loading && !this.errorMessage && this.terminalOrdersTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.loading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.loading;
    }
    render() {
        return (h(StyledHost, { key: '14c0dfe45a6833251f4c2d1d27ea49568f7ac01e' }, h(TableWrapper, { key: '7995d0b2ccb002265769804aa112dca1178d14dd' }, h(TableComponent, { key: 'ddfb54945255a1ae601659b5dee46da8e7fbfb52' }, h(TableHead, { key: '26958541cd82e414d9b079ac18ff69022969a4b8' }, h(TableHeadRow, { key: '1068214ddc3e0003bab2212c0baff74c7e086b96' }, this.terminalOrdersTable.columnData.map((column) => column))), h(TableBody, { key: '7b043e72311e7c956855320b7293a33e41f08da2' }, h(TableLoadingState, { key: 'b2532063645be1e926cfd7dca5b33414d09e5703', columnSpan: this.terminalOrdersTable.columnKeys.length, isLoading: this.loading }), h(TableEmptyState, { key: 'ceec3f0f885e1377afdf36ca2714ebac9b6f7bfc', isEmpty: this.showEmptyState, columnSpan: this.terminalOrdersTable.columnKeys.length }), h(TableErrorState, { key: '2c35baac2f8902e8bf96844f17f57104ba253986', columnSpan: this.terminalOrdersTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData &&
            this.terminalOrdersTable.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: 'f5e1fe9ba78d5cee96e044c60ffaabe45ff3d19d' }, h(TableFootRow, { key: 'ab8c1111b2a1124ba3f0b0bf2deb5893cf4c4ce5' }, h(TableFootCell, { key: 'd463b0e2db8c5d093b38816d78c9176e302fe2c0', colSpan: this.terminalOrdersTable.columnData.length }, h("pagination-menu", { key: '364dfccaa8480e63e51fa3bbdbf4cbb560e9fbbf', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "accountId": ["authPropChanged"],
        "authToken": ["authPropChanged"],
        "pagingParams": ["pagingOrColumnsChanged"],
        "columns": ["pagingOrColumnsChanged"]
    }; }
};

export { JustifiTerminalOrdersList as justifi_terminal_orders_list };
