/*!
 * 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.
 */

import { MaterialReactTable, useMaterialReactTable } from "material-react-table";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Trans, useTranslation } from "../i18n.generated/i18n.js";
import { Typography } from "../Typography.js";
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
const PaginatedTable = ({
  columns = [],
  data = [],
  fetchMoreData,
  getRowId,
  hasError,
  hasRowSelection,
  initialState,
  isFetching,
  onGlobalFilterChange,
  onPaginationChange,
  onRowSelectionChange: onRowSelectionChangeProp,
  rowsPerPage = 10,
  state,
  ToolbarButtons
}) => {
  const {
    t
  } = useTranslation();
  const rowVirtualizerInstanceRef = useRef(null);
  const [columnFilters, setColumnFilters] = useState([]);
  const [globalFilter, setGlobalFilter] = useState();
  useEffect(() => {
    if (globalFilter !== undefined) {
      onGlobalFilterChange?.(globalFilter);
    }
  }, [globalFilter, onGlobalFilterChange]);
  useEffect(() => {
    try {
      rowVirtualizerInstanceRef.current?.scrollToIndex?.(0);
    } catch (error) {
      console.error(error);
    }
  }, [columnFilters, globalFilter]);
  const totalFetchedRows = data.length ?? 0;
  const renderBottomToolbarCustomActions = useCallback(() => fetchMoreData ? _jsx(Typography, {
    children: _jsx(Trans, {
      count: totalFetchedRows,
      i18nKey: "table.fetchedrows.text",
      values: {
        totalRows: totalFetchedRows
      }
    })
  }) : _jsx(Typography, {
    children: _jsx(Trans, {
      count: totalFetchedRows,
      i18nKey: "table.rows.text",
      values: {
        totalRows: totalFetchedRows
      }
    })
  }), [fetchMoreData, totalFetchedRows]);
  const renderTopToolbarCustomActions = useCallback(({
    table
  }) => _jsx(_Fragment, {
    children: ToolbarButtons && _jsx(ToolbarButtons, {
      table: table
    })
  }), [ToolbarButtons]);
  const [rowSelection, setRowSelection] = useState({});
  useEffect(() => {
    onRowSelectionChangeProp?.(rowSelection);
  }, [onRowSelectionChangeProp, rowSelection]);
  const [pagination, setPagination] = useState(initialState?.pagination || {
    pageIndex: 0,
    pageSize: rowsPerPage
  });
  const dataLengthRef = useRef(data.length);
  const updatePagination = useCallback(paginationFunction => {
    if (data.length === dataLengthRef.current) {
      setPagination(previousPagination => {
        const nextPagination = paginationFunction(previousPagination);
        return nextPagination;
      });
    } else {
      dataLengthRef.current = data.length;
    }
  }, [data.length]);
  useEffect(() => {
    const numberOfPages = Math.floor(data.length / pagination.pageSize);
    if (!isFetching && pagination.pageIndex > numberOfPages - 1) {
      fetchMoreData?.();
    }
  }, [data.length, fetchMoreData, isFetching, pagination.pageIndex, pagination.pageSize]);
  useEffect(() => {
    onPaginationChange?.({
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    });
  }, [onPaginationChange, pagination.pageIndex, pagination.pageSize]);
  const modifiedInitialState = useMemo(() => ({
    pagination,
    ...initialState
  }), [initialState, pagination]);
  const modifiedState = useMemo(() => ({
    pagination: {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    },
    rowSelection,
    globalFilter,
    columnFilters,
    ...state
  }), [pagination.pageIndex, pagination.pageSize, rowSelection, globalFilter, columnFilters, state]);
  const muiToolbarAlertBannerProps = useMemo(() => hasError ? {
    children: t("table.error"),
    severity: "error"
  } : {}, [hasError, t]);
  const muiTablePaginationProps = useMemo(() => ({
    rowsPerPageOptions: [],
    showFirstButton: false,
    showLastButton: false
  }), []);
  const muiCheckboxStyles = useCallback(theme => typeof theme.components?.MuiCheckbox?.styleOverrides?.root === "function" ? theme.components?.MuiCheckbox?.styleOverrides?.root?.({
    ownerState: {},
    theme
  }) : "", []);
  const table = 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 _jsx(MaterialReactTable, {
    table: table
  });
};
const MemoizedPaginatedTable = memo(PaginatedTable);
MemoizedPaginatedTable.displayName = "PaginatedTable";
export { MemoizedPaginatedTable as PaginatedTable };
//# sourceMappingURL=PaginatedTable.js.map