import React__default, { useRef } from 'react';
import { useUniqueId } from '../../../utils/uniqueId.mjs';
import { useToast } from './Toast.mjs';
import CircularProgress from '../../../../../../node_modules/@mui/material/CircularProgress/CircularProgress.mjs';
import TablePagination from '../../../../../../node_modules/@mui/material/TablePagination/TablePagination.mjs';
import styled from '../../../../../../node_modules/@mui/material/styles/styled.mjs';
import tablePaginationClasses from '../../../../../../node_modules/@mui/material/TablePagination/tablePaginationClasses.mjs';
import iconButtonClasses from '../../../../../../node_modules/@mui/material/IconButton/iconButtonClasses.mjs';

const DEFAULT_TABLE_ROWS_PER_PAGE = 20;
const LOAD_NEXT_PAGE_ERROR = 'Failed to load the next page.';
const ZERO_RESULTS_MESSAGE = 'No results found.';
const PAGINATED_TABLE_ID = 'paginated-table';
const TablePaginationContainer = styled('div')(({ theme })=>({
        [`& .${tablePaginationClasses.actions} .${iconButtonClasses.root}`]: {
            padding: theme.spacing(1)
        },
        alignItems: 'center',
        display: 'flex',
        justifyContent: 'flex-end',
        padding: 0
    }));
const EmptyTable = styled('div')(({ height, theme })=>({
        alignItems: 'flex-start',
        display: 'flex',
        justifyContent: 'center',
        padding: theme.spacing(4),
        height
    }));
const defaultRowsPerPageOptions = [];
const PaginatedTableCore = ({ currentPage, loadNext, isLoading, metadata, setCurrentPage, rowsPerPage = DEFAULT_TABLE_ROWS_PER_PAGE, rowsPerPageOptions = defaultRowsPerPageOptions, onRowsPerPageChange, keepConsistentContentHeight = true, tablePaginationSx, TableComponent: Table, TypographyComponent: Typography, ...tableProps })=>{
    const { items } = tableProps;
    const tableId = useUniqueId(PAGINATED_TABLE_ID);
    const { openToast } = useToast();
    const tableRowHeight = useRef();
    const currFirstRowIndex = currentPage * rowsPerPage;
    const loadNextHandler = async (newPage)=>{
        tableRowHeight.current = document.querySelector(`#${tableId} tbody tr`)?.clientHeight;
        const totalLoadedResults = items ? items.length : 0;
        if (metadata?.cursor && totalLoadedResults <= newPage * rowsPerPage) {
            try {
                await loadNext();
            } catch  {
                openToast({
                    type: 'error',
                    text: LOAD_NEXT_PAGE_ERROR
                });
            }
        }
    };
    const handleChangePage = async (_, newPage)=>{
        await loadNextHandler(newPage);
        setCurrentPage(newPage);
    };
    const pageResults = items.slice(currFirstRowIndex, currFirstRowIndex + rowsPerPage);
    const showLoading = isLoading;
    const showNoResults = !isLoading && items.length === 0;
    const showEmptyTable = showLoading || showNoResults;
    // [BACK-3158] Some searches will return -1 to indicate that the Total count was too expensive to be returned
    // In that case, we should _always_ show pagination controls
    let countForPagination;
    let moreRowsToShow;
    if (metadata?.total === -1) {
        // Pass -1 to the pagination component to enable pagination for an unknown # of items
        // Unless there's no cursor - in which case we know the total # of items
        countForPagination = metadata.cursor ? -1 : items.length;
        moreRowsToShow = true;
    } else {
        countForPagination = metadata?.total ?? 0;
        moreRowsToShow = (metadata?.total ?? 0) > rowsPerPage;
    }
    const showPagination = !showEmptyTable && moreRowsToShow || rowsPerPageOptions.length > 1;
    const paginationMarginTop = (rowsPerPage - pageResults.length) * (tableRowHeight.current ?? 0) - 1;
    return /*#__PURE__*/ React__default.createElement("div", {
        id: tableId
    }, /*#__PURE__*/ React__default.createElement(Table, {
        ...tableProps,
        items: showEmptyTable ? [] : pageResults
    }), showEmptyTable && /*#__PURE__*/ React__default.createElement(EmptyTable, {
        height: tableRowHeight.current ? Math.min(rowsPerPage, pageResults.length) * tableRowHeight.current : undefined
    }, showLoading && /*#__PURE__*/ React__default.createElement(CircularProgress, {
        color: "inherit"
    }), showNoResults && /*#__PURE__*/ React__default.createElement(Typography, null, ZERO_RESULTS_MESSAGE)), showPagination && /*#__PURE__*/ React__default.createElement(TablePaginationContainer, {
        style: keepConsistentContentHeight ? {
            marginTop: paginationMarginTop
        } : undefined
    }, /*#__PURE__*/ React__default.createElement(TablePagination, {
        sx: tablePaginationSx,
        component: "div",
        count: countForPagination,
        onPageChange: handleChangePage,
        page: currentPage,
        rowsPerPage: rowsPerPage,
        rowsPerPageOptions: rowsPerPageOptions,
        onRowsPerPageChange: onRowsPerPageChange
    })));
};

export { DEFAULT_TABLE_ROWS_PER_PAGE, PaginatedTableCore };
//# sourceMappingURL=PaginatedTable.mjs.map
