"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TableLayoutContent = void 0;
var _styled = _interopRequireDefault(require("@emotion/styled"));
var _materialReactTable = require("material-react-table");
var _react = require("react");
var _Box = require("../../Box.cjs");
var _Button = require("../../Buttons/Button.cjs");
var _MenuButton = require("../../Buttons/MenuButton.cjs");
var _useScrollIndication = require("../../DataTable/useScrollIndication.cjs");
var _i18n = require("../../i18n.generated/i18n.cjs");
var _index = require("../../icons.generated/index.cjs");
var _OdysseyDesignTokensContext = require("../../OdysseyDesignTokensContext.cjs");
var _RowActions = require("./RowActions.cjs");
var _tableConstants = require("./tableConstants.cjs");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/*!
 * Copyright (c) 2024-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 TextWrapper = (0, _styled.default)("div")({
  whiteSpace: "nowrap",
  textOverflow: "ellipsis",
  overflow: "hidden"
});
const RowActionsContainer = (0, _styled.default)("div")({
  display: "flex"
});
const TableLayoutContent = ({
  columns,
  data,
  draggingRow,
  emptyState,
  enableVirtualization,
  getRowId,
  hasRowReordering,
  hasRowSelection,
  isEmpty,
  isLoading,
  isNoResults,
  isRowReorderingDisabled,
  onReorderRows,
  pagination,
  rowReorderingUtilities,
  rowSelection,
  setRowSelection,
  setTableState,
  tableLayoutOptions,
  tableState,
  totalRows
}) => {
  const [isTableContainerScrolledToStart, setIsTableContainerScrolledToStart] = (0, _react.useState)(true);
  const [isTableContainerScrolledToEnd, setIsTableContainerScrolledToEnd] = (0, _react.useState)(true);
  const [tableInnerContainerWidth, setTableInnerContainerWidth] = (0, _react.useState)("100%");
  const shouldUpdateScroll = (0, _react.useRef)(false);
  const tableOuterContainerRef = (0, _react.useRef)(null);
  const tableInnerContainerRef = (0, _react.useRef)(null);
  const tableContentRef = (0, _react.useRef)(null);
  (0, _useScrollIndication.useScrollIndication)({
    setIsTableContainerScrolledToEnd: setIsTableContainerScrolledToEnd,
    setIsTableContainerScrolledToStart: setIsTableContainerScrolledToStart,
    setTableInnerContainerWidth: setTableInnerContainerWidth,
    tableInnerContainer: tableInnerContainerRef.current,
    tableOuterContainer: tableOuterContainerRef.current
  });
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  const {
    t
  } = (0, _i18n.useTranslation)();
  const columnIds = (0, _react.useMemo)(() => {
    return columns.map(column => column.accessorKey) ?? [];
  }, [columns]);
  const columnOrder = (0, _react.useMemo)(() => ["mrt-row-drag", "mrt-row-select", "mrt-row-expand", ...(columnIds?.filter(id => typeof id === "string") || []), "mrt-row-actions"], [columnIds]);
  const rowDensityClassName = (0, _react.useMemo)(() => {
    return tableState.rowDensity === "spacious" ? "MuiTableBody-spacious" : tableState.rowDensity === "compact" ? "MuiTableBody-compact" : "MuiTableBody-default";
  }, [tableState]);
  const defaultCell = (0, _react.useCallback)(({
    cell
  }) => {
    const value = cell.getValue();
    const hasTextWrapping = cell.column.columnDef.hasTextWrapping || cell.column.columnDef.enableWrapping;
    return hasTextWrapping ? value : (0, _jsxRuntime.jsx)(TextWrapper, {
      children: value
    });
  }, []);
  const {
    draggableTableBodyRowClassName,
    dragHandleStyles,
    dragHandleText,
    handleDragHandleKeyDown,
    handleDragHandleOnDragCapture,
    handleDragHandleOnDragEnd,
    resetDraggingAndHoveredRow,
    updateRowOrder
  } = rowReorderingUtilities;
  const renderRowActions = (0, _react.useCallback)(({
    row
  }) => {
    const currentIndex = row.index + (pagination.pageIndex - 1) * pagination.pageSize;
    return (0, _jsxRuntime.jsxs)(RowActionsContainer, {
      children: [tableLayoutOptions.rowActionButtons?.(row.original), (tableLayoutOptions.rowActionMenuItems || hasRowReordering) && (0, _jsxRuntime.jsx)(_MenuButton.MenuButton, {
        ariaLabel: t("table.moreactions.arialabel"),
        buttonVariant: "floating",
        endIcon: (0, _jsxRuntime.jsx)(_index.MoreIcon, {}),
        menuAlignment: "right",
        size: "small",
        children: (0, _jsxRuntime.jsx)(_RowActions.RowActions, {
          isRowReorderingDisabled: isRowReorderingDisabled,
          row: row,
          rowActionMenuItems: tableLayoutOptions.rowActionMenuItems,
          rowIndex: currentIndex,
          totalRows: totalRows,
          updateRowOrder: hasRowReordering && onReorderRows ? updateRowOrder : undefined
        })
      })]
    });
  }, [hasRowReordering, isRowReorderingDisabled, onReorderRows, pagination.pageIndex, pagination.pageSize, t, tableLayoutOptions, totalRows, updateRowOrder]);
  const innerWidthStyle = (0, _react.useMemo)(() => ({
    width: tableInnerContainerWidth
  }), [tableInnerContainerWidth]);
  const emptyStateContainer = (0, _react.useCallback)(() => (0, _jsxRuntime.jsx)(_Box.Box, {
    sx: innerWidthStyle,
    children: emptyState
  }), [innerWidthStyle, emptyState]);
  (0, _react.useEffect)(() => {
    if (enableVirtualization) {
      shouldUpdateScroll.current = true;
    }
  }, [enableVirtualization, pagination]);
  (0, _react.useEffect)(() => {
    if (shouldUpdateScroll.current && tableContentRef.current && typeof tableInnerContainerRef.current?.scrollTo !== "undefined") {
      tableInnerContainerRef.current?.scrollTo(0, tableContentRef.current.clientHeight);
      shouldUpdateScroll.current = false;
    }
  }, [data]);
  const shouldDisplayRowActions = (0, _react.useMemo)(() => hasRowReordering === true && onReorderRows || tableLayoutOptions.rowActionButtons || tableLayoutOptions.rowActionMenuItems ? true : false, [hasRowReordering, onReorderRows, tableLayoutOptions.rowActionButtons, tableLayoutOptions.rowActionMenuItems]);
  const hasColumnWithGrow = columns.some(column => column.grow === true);
  const dataTable = (0, _materialReactTable.useMaterialReactTable)({
    data: !isEmpty && !isNoResults ? data : [],
    columns,
    getRowId,
    state: {
      sorting: tableState.columnSorting,
      columnVisibility: tableState.columnVisibility,
      isLoading,
      rowSelection,
      columnOrder
    },
    icons: {
      ArrowDownwardIcon: _index.ArrowDownIcon,
      DragHandleIcon: _index.DragIndicatorIcon,
      SyncAltIcon: _index.ArrowUnsortedIcon,
      ExpandMoreIcon: _index.ChevronDownIcon
    },
    ..._tableConstants.dataTableImmutableSettings,
    displayColumnDefOptions: {
      ..._tableConstants.displayColumnDefOptions,
      "mrt-row-actions": {
        header: "",
        grow: !hasColumnWithGrow,
        muiTableBodyCellProps: {
          align: "right",
          sx: {
            overflow: "visible",
            width: "unset"
          },
          className: "ods-actions-cell"
        },
        muiTableHeadCellProps: {
          align: "right",
          sx: {
            width: "unset"
          },
          className: "ods-actions-cell",
          children: (0, _jsxRuntime.jsxs)(_Box.Box, {
            sx: {
              display: "flex",
              visibility: "hidden"
            },
            children: [tableLayoutOptions.rowActionButtons && tableLayoutOptions.rowActionButtons(), (hasRowReordering === true && onReorderRows || tableLayoutOptions.rowActionMenuItems) && (0, _jsxRuntime.jsx)(_Box.Box, {
              children: (0, _jsxRuntime.jsx)(_Button.Button, {
                ariaLabel: t("table.moreactions.arialabel"),
                endIcon: (0, _jsxRuntime.jsx)(_index.MoreIcon, {}),
                isDisabled: true,
                size: "small",
                variant: "floating"
              })
            })]
          })
        }
      }
    },
    muiTableProps: {
      ref: tableContentRef,
      className: !shouldDisplayRowActions && tableLayoutOptions.hasColumnResizing ? hasColumnWithGrow ? "ods-hide-spacer-column" : "ods-hide-spacer-column ods-column-grow" : ""
    },
    muiTableContainerProps: {
      ref: tableInnerContainerRef
    },
    muiTableBodyProps: () => ({
      className: rowDensityClassName,
      tabIndex: 0,
      sx: isEmpty || isNoResults ? {
        height: "unset"
      } : undefined
    }),
    enableColumnResizing: tableLayoutOptions.hasColumnResizing,
    defaultColumn: {
      Cell: defaultCell
    },
    enableRowActions: hasRowReordering === true && onReorderRows || tableLayoutOptions.rowActionButtons || tableLayoutOptions.rowActionMenuItems ? true : false,
    renderRowActions: ({
      row
    }) => renderRowActions({
      row
    }),
    enableRowOrdering: hasRowReordering && Boolean(onReorderRows),
    enableRowDragging: hasRowReordering && Boolean(onReorderRows),
    muiDetailPanelProps: ({
      row
    }) => ({
      sx: {
        paddingBlock: row.getIsExpanded() ? `${odysseyDesignTokens.Spacing3} !important` : undefined
      }
    }),
    muiTableBodyRowProps: ({
      table,
      row,
      isDetailPanel
    }) => ({
      className: draggableTableBodyRowClassName({
        currentRowId: row.id,
        draggingRowId: draggingRow?.id,
        hoveredRowId: table.getState().hoveredRow?.id
      }),
      sx: isDetailPanel ? {
        paddingBlock: "0 !important",
        border: 0,
        ["&:hover"]: {
          backgroundColor: `${odysseyDesignTokens.HueNeutralWhite} !important`
        }
      } : {}
    }),
    muiRowDragHandleProps: ({
      table,
      row
    }) => ({
      onKeyDown: event => handleDragHandleKeyDown({
        table,
        row,
        event
      }),
      onBlur: () => resetDraggingAndHoveredRow(table),
      onDragEnd: () => handleDragHandleOnDragEnd(table),
      onDragCapture: () => handleDragHandleOnDragCapture(table),
      disabled: isRowReorderingDisabled,
      sx: dragHandleStyles,
      ...dragHandleText
    }),
    renderDetailPanel: tableLayoutOptions.renderDetailPanel,
    enableRowVirtualization: enableVirtualization,
    muiTableHeadCellProps: ({
      column: currentColumn
    }) => ({
      className: tableState.columnSorting.find(sortedColumn => sortedColumn.id === currentColumn.id) ? "isSorted" : "isUnsorted"
    }),
    muiTableBodyCellProps: ({
      column
    }) => ({
      className: column.getIsResizing() ? "isResizing" : ""
    }),
    enableSorting: tableLayoutOptions.hasSorting === true,
    onSortingChange: sortingUpdater => {
      const newSortVal = typeof sortingUpdater === "function" ? sortingUpdater(tableState.columnSorting) : tableState.columnSorting;
      setTableState(prevState => ({
        ...prevState,
        columnSorting: newSortVal
      }));
    },
    enableRowSelection: hasRowSelection,
    onRowSelectionChange: setRowSelection,
    renderEmptyRowsFallback: emptyStateContainer,
    localization: {
      collapse: t("table.rowexpansion.collapse"),
      collapseAll: t("table.rowexpansion.collapseall"),
      expand: t("table.rowexpansion.expand"),
      expandAll: t("table.rowexpansion.expandall")
    }
  });
  return (0, _jsxRuntime.jsx)(_tableConstants.ScrollableTableContainer, {
    isScrollableEnd: !isTableContainerScrolledToEnd,
    isScrollableStart: !isTableContainerScrolledToStart,
    odysseyDesignTokens: odysseyDesignTokens,
    ref: tableOuterContainerRef,
    children: (0, _jsxRuntime.jsx)(_materialReactTable.MRT_TableContainer, {
      table: dataTable
    })
  });
};
const MemoizedTableLayoutContent = exports.TableLayoutContent = (0, _react.memo)(TableLayoutContent);
MemoizedTableLayoutContent.displayName = "TableLayoutContent";
//# sourceMappingURL=TableLayoutContent.cjs.map