"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PaginatedTable = void 0;
var _materialReactTable = require("material-react-table");
var _react = require("react");
var _i18n = require("../i18n.generated/i18n.cjs");
var _Typography = require("../Typography.cjs");
var _jsxRuntime = require("react/jsx-runtime");
/*!
 * Copyright (c) 2022-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */

const PaginatedTable = ({
  columns = [],
  data = [],
  fetchMoreData,
  getRowId,
  hasError,
  hasRowSelection,
  initialState,
  isFetching,
  onGlobalFilterChange,
  onPaginationChange,
  onRowSelectionChange: onRowSelectionChangeProp,
  rowsPerPage = 10,
  state,
  ToolbarButtons
}) => {
  const {
    t
  } = (0, _i18n.useTranslation)();
  const rowVirtualizerInstanceRef = (0, _react.useRef)(null);
  const [columnFilters, setColumnFilters] = (0, _react.useState)([]);
  const [globalFilter, setGlobalFilter] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    if (globalFilter !== undefined) {
      onGlobalFilterChange?.(globalFilter);
    }
  }, [globalFilter, onGlobalFilterChange]);
  (0, _react.useEffect)(() => {
    try {
      rowVirtualizerInstanceRef.current?.scrollToIndex?.(0);
    } catch (error) {
      console.error(error);
    }
  }, [columnFilters, globalFilter]);
  const totalFetchedRows = data.length ?? 0;
  const renderBottomToolbarCustomActions = (0, _react.useCallback)(() => fetchMoreData ? (0, _jsxRuntime.jsx)(_Typography.Typography, {
    children: (0, _jsxRuntime.jsx)(_i18n.Trans, {
      count: totalFetchedRows,
      i18nKey: "table.fetchedrows.text",
      values: {
        totalRows: totalFetchedRows
      }
    })
  }) : (0, _jsxRuntime.jsx)(_Typography.Typography, {
    children: (0, _jsxRuntime.jsx)(_i18n.Trans, {
      count: totalFetchedRows,
      i18nKey: "table.rows.text",
      values: {
        totalRows: totalFetchedRows
      }
    })
  }), [fetchMoreData, totalFetchedRows]);
  const renderTopToolbarCustomActions = (0, _react.useCallback)(({
    table
  }) => (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
    children: ToolbarButtons && (0, _jsxRuntime.jsx)(ToolbarButtons, {
      table: table
    })
  }), [ToolbarButtons]);
  const [rowSelection, setRowSelection] = (0, _react.useState)({});
  (0, _react.useEffect)(() => {
    onRowSelectionChangeProp?.(rowSelection);
  }, [onRowSelectionChangeProp, rowSelection]);
  const [pagination, setPagination] = (0, _react.useState)(initialState?.pagination || {
    pageIndex: 0,
    pageSize: rowsPerPage
  });
  const dataLengthRef = (0, _react.useRef)(data.length);
  const updatePagination = (0, _react.useCallback)(paginationFunction => {
    if (data.length === dataLengthRef.current) {
      setPagination(previousPagination => {
        const nextPagination = paginationFunction(previousPagination);
        return nextPagination;
      });
    } else {
      dataLengthRef.current = data.length;
    }
  }, [data.length]);
  (0, _react.useEffect)(() => {
    const numberOfPages = Math.floor(data.length / pagination.pageSize);
    if (!isFetching && pagination.pageIndex > numberOfPages - 1) {
      fetchMoreData?.();
    }
  }, [data.length, fetchMoreData, isFetching, pagination.pageIndex, pagination.pageSize]);
  (0, _react.useEffect)(() => {
    onPaginationChange?.({
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    });
  }, [onPaginationChange, pagination.pageIndex, pagination.pageSize]);
  const modifiedInitialState = (0, _react.useMemo)(() => ({
    pagination,
    ...initialState
  }), [initialState, pagination]);
  const modifiedState = (0, _react.useMemo)(() => ({
    pagination: {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    },
    rowSelection,
    globalFilter,
    columnFilters,
    ...state
  }), [pagination.pageIndex, pagination.pageSize, rowSelection, globalFilter, columnFilters, state]);
  const muiToolbarAlertBannerProps = (0, _react.useMemo)(() => hasError ? {
    children: t("table.error"),
    severity: "error"
  } : {}, [hasError, t]);
  const muiTablePaginationProps = (0, _react.useMemo)(() => ({
    rowsPerPageOptions: [],
    showFirstButton: false,
    showLastButton: false
  }), []);
  const muiCheckboxStyles = (0, _react.useCallback)(theme => typeof theme.components?.MuiCheckbox?.styleOverrides?.root === "function" ? theme.components?.MuiCheckbox?.styleOverrides?.root?.({
    ownerState: {},
    theme
  }) : "", []);
  const table = (0, _materialReactTable.useMaterialReactTable)({
    columns: columns,
    data: data,
    enableMultiRowSelection: hasRowSelection,
    enablePagination: true,
    enableRowSelection: hasRowSelection,
    enableSorting: false,
    getRowId: getRowId,
    initialState: modifiedInitialState,
    muiSelectAllCheckboxProps: {
      sx: muiCheckboxStyles
    },
    muiSelectCheckboxProps: {
      sx: muiCheckboxStyles
    },
    muiPaginationProps: muiTablePaginationProps,
    muiToolbarAlertBannerProps: muiToolbarAlertBannerProps,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    onPaginationChange: updatePagination,
    onRowSelectionChange: setRowSelection,
    renderBottomToolbarCustomActions: renderBottomToolbarCustomActions,
    renderTopToolbarCustomActions: renderTopToolbarCustomActions,
    rowVirtualizerInstanceRef: rowVirtualizerInstanceRef,
    rowVirtualizerOptions: {
      overscan: 4
    },
    state: modifiedState
  });
  return (0, _jsxRuntime.jsx)(_materialReactTable.MaterialReactTable, {
    table: table
  });
};
const MemoizedPaginatedTable = exports.PaginatedTable = (0, _react.memo)(PaginatedTable);
MemoizedPaginatedTable.displayName = "PaginatedTable";
//# sourceMappingURL=PaginatedTable.cjs.map