'use strict';

var reactTable = require('@tanstack/react-table');
var classnames = require('classnames');
var React = require('react');
var jobberHooks = require('@jobber/hooks');
var Glimmer = require('./Glimmer-cjs.js');
var tslib_es6 = require('./tslib.es6-cjs.js');
var Select_index = require('./Select/index.cjs');
var Button = require('./Button-cjs.js');
var Text = require('./Text-cjs.js');
var DataTableTable = require('./DataTableTable-cjs.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.createElement("tbody", null, Array.from(Array(loaderRows).keys()).map(row => (React.createElement("tr", { key: row }, Array.from(Array(loaderColumns).keys()).map(arr => (React.createElement("td", { key: arr },
        React.createElement(Glimmer.Glimmer, null)))))))));
}

function Body({ table, onRowClick, emptyState, loading, }) {
    const bodyRowClasses = classnames({ [styles$2.clickableRow]: !!onRowClick });
    const handleRowClick = React.useCallback((row) => () => {
        if (onRowClick == undefined)
            return;
        onRowClick(row);
    }, [onRowClick]);
    if (loading) {
        return React.createElement(BodyLoading, { table: table });
    }
    return (React.createElement(React.Fragment, null, table.getRowModel().rows.length ? (React.createElement("tbody", null, table.getRowModel().rows.map(row => {
        return (React.createElement("tr", { key: row.id, onClick: handleRowClick(row), className: bodyRowClasses }, row.getVisibleCells().map(cell => {
            return (React.createElement("td", { key: cell.id, style: {
                    width: cell.column.getSize(),
                    minWidth: cell.column.columnDef.minSize,
                    maxWidth: cell.column.columnDef.maxSize,
                } }, reactTable.flexRender(cell.column.columnDef.cell, cell.getContext())));
        })));
    }))) : (React.createElement("tbody", null,
        React.createElement("tr", { className: bodyRowClasses },
            React.createElement("td", { colSpan: table.getAllColumns().length, className: styles$2.emptyStateCell },
                React.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 = tslib_es6.__rest(_b, ["state"]);
    const _c = getSortingSettings(options === null || options === void 0 ? void 0 : options.sorting), { state: sortingState } = _c, restSortingSettings = tslib_es6.__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: reactTable.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 = reactTable.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 = reactTable.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 = React.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.createElement("div", { className: styles$1.pagination },
        React.createElement("div", { className: styles$1.paginationInfo }, !loading ? React.createElement(Text.Text, null, "No items") : React.createElement(Glimmer.Glimmer, { width: 200 })))) : (React.createElement("div", { className: styles$1.pagination },
        React.createElement("div", { className: styles$1.paginationInfo }, `Showing ${firstPosition}-${secondPosition} of ${totalRows} items`),
        React.createElement("div", { className: styles$1.paginationNav },
            React.createElement("div", { className: styles$1.paginationSelect },
                React.createElement(Select_index.Select, { value: table.getState().pagination.pageSize, onChange: value => {
                        table.setPageSize(Number(value));
                    }, size: "small" }, itemsPerPageOptions.map(numOfPages => (React.createElement(Select_index.Option, { key: numOfPages, value: numOfPages }, numOfPages)))),
                React.createElement("span", { className: styles$1.paginationSelectLabel }, "per page")),
            React.createElement("div", { className: styles$1.paginationButtons },
                React.createElement(Button.Button, { type: "secondary", variation: "subtle", icon: "arrowLeft", ariaLabel: "arrowLeft", onClick: () => {
                        table.previousPage();
                        onPageChange();
                    }, disabled: !table.getCanPreviousPage() }),
                React.createElement(Button.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.createElement("tfoot", { "data-testid": "data-table-desktop-footer" }, table.getFooterGroups().map(footerGroup => (React.createElement("tr", { key: footerGroup.id }, footerGroup.headers.map(header => (React.createElement("th", { key: header.id, style: {
        width: header.getSize(),
        minWidth: header.column.columnDef.minSize,
        maxWidth: header.column.columnDef.maxSize,
    } }, reactTable.flexRender(header.column.columnDef.footer, header.getContext())))))))));
const HandheldView = ({ table }) => (React.createElement("div", { className: styles.mobileFooterContainer, "data-testid": "data-table-handheld-footer" }, table.getFooterGroups().map(footerGroup => (React.createElement("div", { key: footerGroup.id }, footerGroup.headers
    .filter(header => header.column.columnDef.footer)
    .map((header, index) => (React.createElement(React.Fragment, null, index === 0 ? (React.createElement("div", { className: styles.mobileFooterRow }, reactTable.flexRender(header.column.columnDef.footer, header.getContext()))) : (React.createElement("div", { className: styles.mobileFooterRow, key: footerGroup.id },
    reactTable.flexRender(header.column.columnDef.header, header.getContext()),
    React.createElement("div", { className: styles.mobileFooterRowData }, reactTable.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.createElement(HandheldView, { table: table })) : (React.createElement(DesktopView, { table: table }));
    }
    return null;
};

function Header({ table, stickyHeader, sorting, onRowClick, }) {
    const stickyClass = classnames({ [styles$2.stickyHeader]: stickyHeader });
    return (React.createElement("thead", { className: stickyClass }, table.getHeaderGroups().map(headerGroup => (React.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.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.createElement("div", null,
            reactTable.flexRender(header.column.columnDef.header, header.getContext()),
            header.column.getCanSort() &&
                sorting &&
                !header.column.getIsSorted() && (React.createElement(DataTableTable.SortIcon, { direction: DataTableTable.SortDirection.equilibrium })),
            {
                asc: React.createElement(DataTableTable.SortIcon, { direction: DataTableTable.SortDirection.ascending }),
                desc: React.createElement(DataTableTable.SortIcon, { direction: DataTableTable.SortDirection.descending }),
            }[header.column.getIsSorted()]))));
    }))))));
}

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

exports.DataTable = DataTable;
