import { flexRender, getCoreRowModel, getPaginationRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table';
import classnames from 'classnames';
import React__default, { useCallback, useMemo } from 'react';
import { useResizeObserver, Breakpoints } from '@jobber/hooks';
import { G as Glimmer } from './Glimmer-es.js';
import { _ as __rest } from './tslib.es6-es.js';
import { Select, Option as SelectOption } from './Select/index.mjs';
import { B as Button } from './Button-es.js';
import { T as Text } from './Text-es.js';
import { S as SortIcon, a as SortDirection, m as DataTableTable, f as DataTableHeader, g as DataTableHeaderCell, j as DataTableRow, c as DataTableCell, k as DataTableRowActions, D as DataTableActions, b as DataTableBody, d as DataTableContainer, l as DataTableSortableHeader, e as DataTableFooter, h as DataTablePagination, i as DataTablePaginationButton } from './DataTableTable-es.js';

var styles$2 = {"dataTableContainer":"_3IHK46TSBOI-","tableContainer":"_8CMtSx4qamA-","table":"bNYpzdn5rPc-","pinFirstColumn":"lKXqbcsnCFs-","emptyStateCell":"i-x8vss2hcI-","stickyHeader":"eWffzdKfJH0-","pinFirstHeaderSortable":"aGF6t8l8iUk-","sortableColumn":"W0kYDUxPkqI-","clickableRow":"vWFyXrAaFtQ-","emptyState":"_8L7icG7E530-","spinning":"O1cxELzWgmM-"};

function BodyLoading({ table }) {
    const loaderRows = table.getState().pagination.pageSize;
    const loaderColumns = table.getAllColumns().length;
    return (React__default.createElement("tbody", null, Array.from(Array(loaderRows).keys()).map(row => (React__default.createElement("tr", { key: row }, Array.from(Array(loaderColumns).keys()).map(arr => (React__default.createElement("td", { key: arr },
        React__default.createElement(Glimmer, null)))))))));
}

function Body({ table, onRowClick, emptyState, loading, }) {
    const bodyRowClasses = classnames({ [styles$2.clickableRow]: !!onRowClick });
    const handleRowClick = useCallback((row) => () => {
        if (onRowClick == undefined)
            return;
        onRowClick(row);
    }, [onRowClick]);
    if (loading) {
        return React__default.createElement(BodyLoading, { table: table });
    }
    return (React__default.createElement(React__default.Fragment, null, table.getRowModel().rows.length ? (React__default.createElement("tbody", null, table.getRowModel().rows.map(row => {
        return (React__default.createElement("tr", { key: row.id, onClick: handleRowClick(row), className: bodyRowClasses }, row.getVisibleCells().map(cell => {
            return (React__default.createElement("td", { key: cell.id, style: {
                    width: cell.column.getSize(),
                    minWidth: cell.column.columnDef.minSize,
                    maxWidth: cell.column.columnDef.maxSize,
                } }, flexRender(cell.column.columnDef.cell, cell.getContext())));
        })));
    }))) : (React__default.createElement("tbody", null,
        React__default.createElement("tr", { className: bodyRowClasses },
            React__default.createElement("td", { colSpan: table.getAllColumns().length, className: styles$2.emptyStateCell },
                React__default.createElement("div", { className: styles$2.emptyState }, emptyState)))))));
}

function createTableSettings(data, columns, options) {
    var _a;
    const _b = getPaginationSettings(options === null || options === void 0 ? void 0 : options.pagination), { state: paginationState } = _b, restPaginationSettings = __rest(_b, ["state"]);
    const _c = getSortingSettings(options === null || options === void 0 ? void 0 : options.sorting), { state: sortingState } = _c, restSortingSettings = __rest(_c, ["state"]);
    let initialPatinationState;
    if ((_a = options === null || options === void 0 ? void 0 : options.pagination) === null || _a === void 0 ? void 0 : _a.itemsPerPage) {
        initialPatinationState = {
            pageIndex: 0,
            pageSize: options.pagination.itemsPerPage[0],
        };
    }
    const tableSettings = Object.assign(Object.assign(Object.assign({ data,
        columns, state: Object.assign(Object.assign({}, paginationState), sortingState), getCoreRowModel: getCoreRowModel() }, restPaginationSettings), restSortingSettings), { initialState: {
            pagination: initialPatinationState,
        } });
    return tableSettings;
}
function getPaginationSettings(pagination) {
    const paginationSettings = {};
    if (!pagination) {
        return paginationSettings;
    }
    const { manualPagination } = pagination;
    paginationSettings.manualPagination = manualPagination;
    if (manualPagination) {
        const { state, pageCount, onPaginationChange } = pagination;
        paginationSettings.state = { pagination: state };
        paginationSettings.pageCount = pageCount;
        paginationSettings.onPaginationChange = onPaginationChange;
    }
    else {
        paginationSettings.getPaginationRowModel = getPaginationRowModel();
    }
    return paginationSettings;
}
function getSortingSettings(sorting) {
    const sortingSettings = {};
    if (!sorting)
        return sortingSettings;
    const { manualSorting } = sorting;
    sortingSettings.manualSorting = manualSorting;
    if (manualSorting) {
        const { onSortingChange, state, enableSortingRemoval } = sorting;
        sortingSettings.state = { sorting: state };
        sortingSettings.onSortingChange = onSortingChange;
        sortingSettings.enableSortingRemoval = enableSortingRemoval !== null && enableSortingRemoval !== void 0 ? enableSortingRemoval : true;
    }
    else {
        sortingSettings.getSortedRowModel = getSortedRowModel();
    }
    return sortingSettings;
}

var styles$1 = {"pagination":"_5TLZRabskzI-","paginationInfo":"k8VFFgHUPZ4-","paginationNav":"SfaHBP7KC3Y-","paginationSelect":"E4zFf5oEm-Y-","paginationSelectLabel":"N4LhT5occ94-","paginationButtons":"HQPsyRjssL0-","spinning":"YHT2Mg0618I-"};

const defaultItemsPerPageOptions = ["10", "20", "30", "40", "50"];
function Pagination({ table, itemsPerPage, totalItems, loading, onPageChange, }) {
    const { pageIndex, pageSize } = table.getState().pagination;
    const totalRows = totalItems;
    const firstPosition = pageIndex * pageSize + 1;
    const secondPosition = Math.min(totalRows, pageSize * (pageIndex + 1));
    const itemsPerPageOptions = useMemo(() => { var _a; return (_a = itemsPerPage === null || itemsPerPage === void 0 ? void 0 : itemsPerPage.map(item => String(item))) !== null && _a !== void 0 ? _a : defaultItemsPerPageOptions; }, [itemsPerPage]);
    return secondPosition <= 0 ? (React__default.createElement("div", { className: styles$1.pagination },
        React__default.createElement("div", { className: styles$1.paginationInfo }, !loading ? React__default.createElement(Text, null, "No items") : React__default.createElement(Glimmer, { width: 200 })))) : (React__default.createElement("div", { className: styles$1.pagination },
        React__default.createElement("div", { className: styles$1.paginationInfo }, `Showing ${firstPosition}-${secondPosition} of ${totalRows} items`),
        React__default.createElement("div", { className: styles$1.paginationNav },
            React__default.createElement("div", { className: styles$1.paginationSelect },
                React__default.createElement(Select, { value: table.getState().pagination.pageSize, onChange: value => {
                        table.setPageSize(Number(value));
                    }, size: "small" }, itemsPerPageOptions.map(numOfPages => (React__default.createElement(SelectOption, { key: numOfPages, value: numOfPages }, numOfPages)))),
                React__default.createElement("span", { className: styles$1.paginationSelectLabel }, "per page")),
            React__default.createElement("div", { className: styles$1.paginationButtons },
                React__default.createElement(Button, { type: "secondary", variation: "subtle", icon: "arrowLeft", ariaLabel: "arrowLeft", onClick: () => {
                        table.previousPage();
                        onPageChange();
                    }, disabled: !table.getCanPreviousPage() }),
                React__default.createElement(Button, { type: "secondary", variation: "subtle", icon: "arrowRight", ariaLabel: "arrowRight", onClick: () => {
                        table.nextPage();
                        onPageChange();
                    }, disabled: !table.getCanNextPage() })))));
}

var styles = {"mobileFooterContainer":"wMM6V80Rt-w-","mobileFooterRow":"HAoSIniVNvI-","mobileFooterRowData":"mNGvTIKaQIA-","spinning":"u7HdA4nq7qM-"};

const DesktopView = ({ table }) => (React__default.createElement("tfoot", { "data-testid": "data-table-desktop-footer" }, table.getFooterGroups().map(footerGroup => (React__default.createElement("tr", { key: footerGroup.id }, footerGroup.headers.map(header => (React__default.createElement("th", { key: header.id, style: {
        width: header.getSize(),
        minWidth: header.column.columnDef.minSize,
        maxWidth: header.column.columnDef.maxSize,
    } }, flexRender(header.column.columnDef.footer, header.getContext())))))))));
const HandheldView = ({ table }) => (React__default.createElement("div", { className: styles.mobileFooterContainer, "data-testid": "data-table-handheld-footer" }, table.getFooterGroups().map(footerGroup => (React__default.createElement("div", { key: footerGroup.id }, footerGroup.headers
    .filter(header => header.column.columnDef.footer)
    .map((header, index) => (React__default.createElement(React__default.Fragment, null, index === 0 ? (React__default.createElement("div", { className: styles.mobileFooterRow }, flexRender(header.column.columnDef.footer, header.getContext()))) : (React__default.createElement("div", { className: styles.mobileFooterRow, key: footerGroup.id },
    flexRender(header.column.columnDef.header, header.getContext()),
    React__default.createElement("div", { className: styles.mobileFooterRowData }, flexRender(header.column.columnDef.footer, header.getContext()))))))))))));
const Footer = ({ table, viewType = "handheld", }) => {
    const hasFooter = table
        .getAllColumns()
        .find(column => column.columnDef.footer);
    if (hasFooter) {
        return viewType === "handheld" ? (React__default.createElement(HandheldView, { table: table })) : (React__default.createElement(DesktopView, { table: table }));
    }
    return null;
};

function Header({ table, stickyHeader, sorting, onRowClick, }) {
    const stickyClass = classnames({ [styles$2.stickyHeader]: stickyHeader });
    return (React__default.createElement("thead", { className: stickyClass }, table.getHeaderGroups().map(headerGroup => (React__default.createElement("tr", { key: headerGroup.id }, headerGroup.headers.map(header => {
        const isSorting = sorting && header.column.getCanSort();
        const headingCellInlineStyle = {
            width: header.getSize(),
            minWidth: header.column.columnDef.minSize,
            maxWidth: header.column.columnDef.maxSize,
        };
        if (isSorting) {
            headingCellInlineStyle.paddingRight = 0;
        }
        return (React__default.createElement("th", { key: header.id, colSpan: header.colSpan, className: isSorting
                ? classnames(styles$2.sortableColumn, {
                    [styles$2.pinFirstHeaderSortable]: !!onRowClick,
                })
                : "", onClick: sorting ? header.column.getToggleSortingHandler() : undefined, style: headingCellInlineStyle }, header.isPlaceholder ? null : (React__default.createElement("div", null,
            flexRender(header.column.columnDef.header, header.getContext()),
            header.column.getCanSort() &&
                sorting &&
                !header.column.getIsSorted() && (React__default.createElement(SortIcon, { direction: SortDirection.equilibrium })),
            {
                asc: React__default.createElement(SortIcon, { direction: SortDirection.ascending }),
                desc: React__default.createElement(SortIcon, { direction: SortDirection.descending }),
            }[header.column.getIsSorted()]))));
    }))))));
}

function DataTable({ data, columns, pagination, sorting, height, stickyHeader, pinFirstColumn, onRowClick, emptyState, loading = false, }) {
    const [ref, { exactWidth }] = useResizeObserver();
    const tableSettings = createTableSettings(data, columns, {
        pagination,
        sorting,
    });
    const tableClasses = classnames(styles$2.table, {
        [styles$2.pinFirstColumn]: pinFirstColumn,
    });
    const table = useReactTable(tableSettings);
    return (React__default.createElement("div", { className: styles$2.dataTableContainer },
        React__default.createElement("div", { "data-testid": "ATL-DataTable-Container", className: styles$2.tableContainer, style: { height }, ref: ref },
            React__default.createElement("table", { className: tableClasses },
                React__default.createElement(Header, { table: table, sorting: sorting, onRowClick: onRowClick, stickyHeader: stickyHeader }),
                React__default.createElement(Body, { table: table, onRowClick: onRowClick, emptyState: emptyState, loading: loading }),
                table.getRowModel().rows.length &&
                    exactWidth &&
                    exactWidth > Breakpoints.small ? (React__default.createElement(Footer, { table: table, viewType: "desktop" })) : null)),
        table.getRowModel().rows.length &&
            exactWidth &&
            exactWidth <= Breakpoints.small ? (React__default.createElement(Footer, { table: table })) : null,
        pagination && (React__default.createElement(Pagination, { table: table, itemsPerPage: pagination.itemsPerPage, totalItems: pagination.manualPagination
                ? pagination.totalItems
                : table.getCoreRowModel().rows.length, loading: loading, onPageChange: () => { var _a; return (_a = ref.current) === null || _a === void 0 ? void 0 : _a.scrollTo(0, 0); } }))));
}
DataTable.Table = DataTableTable;
DataTable.Header = DataTableHeader;
DataTable.HeaderCell = DataTableHeaderCell;
DataTable.Row = DataTableRow;
DataTable.Cell = DataTableCell;
DataTable.RowActions = DataTableRowActions;
DataTable.Actions = DataTableActions;
DataTable.Body = DataTableBody;
DataTable.Container = DataTableContainer;
DataTable.SortableHeader = DataTableSortableHeader;
DataTable.Footer = DataTableFooter;
DataTable.Pagination = DataTablePagination;
DataTable.PaginationButton = DataTablePaginationButton;

export { DataTable as D };
