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

import styled from "@emotion/styled";
import { MRT_TableContainer, useMaterialReactTable } from "material-react-table";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Box } from "../../Box.js";
import { Button } from "../../Buttons/Button.js";
import { MenuButton } from "../../Buttons/MenuButton.js";
import { useScrollIndication } from "../../DataTable/useScrollIndication.js";
import { useTranslation } from "../../i18n.generated/i18n.js";
import { ArrowDownIcon, ArrowUnsortedIcon, ChevronDownIcon, DragIndicatorIcon, MoreIcon } from "../../icons.generated/index.js";
import { useOdysseyDesignTokens } from "../../OdysseyDesignTokensContext.js";
import { RowActions } from "./RowActions.js";
import { dataTableImmutableSettings, displayColumnDefOptions, ScrollableTableContainer } from "./tableConstants.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const TextWrapper = styled("div")({
  whiteSpace: "nowrap",
  textOverflow: "ellipsis",
  overflow: "hidden"
});
const RowActionsContainer = styled("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] = useState(true);
  const [isTableContainerScrolledToEnd, setIsTableContainerScrolledToEnd] = useState(true);
  const [tableInnerContainerWidth, setTableInnerContainerWidth] = useState("100%");
  const shouldUpdateScroll = useRef(false);
  const tableOuterContainerRef = useRef(null);
  const tableInnerContainerRef = useRef(null);
  const tableContentRef = useRef(null);
  useScrollIndication({
    setIsTableContainerScrolledToEnd: setIsTableContainerScrolledToEnd,
    setIsTableContainerScrolledToStart: setIsTableContainerScrolledToStart,
    setTableInnerContainerWidth: setTableInnerContainerWidth,
    tableInnerContainer: tableInnerContainerRef.current,
    tableOuterContainer: tableOuterContainerRef.current
  });
  const odysseyDesignTokens = useOdysseyDesignTokens();
  const {
    t
  } = useTranslation();
  const columnIds = useMemo(() => {
    return columns.map(column => column.accessorKey) ?? [];
  }, [columns]);
  const columnOrder = useMemo(() => ["mrt-row-drag", "mrt-row-select", "mrt-row-expand", ...(columnIds?.filter(id => typeof id === "string") || []), "mrt-row-actions"], [columnIds]);
  const rowDensityClassName = useMemo(() => {
    return tableState.rowDensity === "spacious" ? "MuiTableBody-spacious" : tableState.rowDensity === "compact" ? "MuiTableBody-compact" : "MuiTableBody-default";
  }, [tableState]);
  const defaultCell = useCallback(({
    cell
  }) => {
    const value = cell.getValue();
    const hasTextWrapping = cell.column.columnDef.hasTextWrapping || cell.column.columnDef.enableWrapping;
    return hasTextWrapping ? value : _jsx(TextWrapper, {
      children: value
    });
  }, []);
  const {
    draggableTableBodyRowClassName,
    dragHandleStyles,
    dragHandleText,
    handleDragHandleKeyDown,
    handleDragHandleOnDragCapture,
    handleDragHandleOnDragEnd,
    resetDraggingAndHoveredRow,
    updateRowOrder
  } = rowReorderingUtilities;
  const renderRowActions = useCallback(({
    row
  }) => {
    const currentIndex = row.index + (pagination.pageIndex - 1) * pagination.pageSize;
    return _jsxs(RowActionsContainer, {
      children: [tableLayoutOptions.rowActionButtons?.(row.original), (tableLayoutOptions.rowActionMenuItems || hasRowReordering) && _jsx(MenuButton, {
        ariaLabel: t("table.moreactions.arialabel"),
        buttonVariant: "floating",
        endIcon: _jsx(MoreIcon, {}),
        menuAlignment: "right",
        size: "small",
        children: _jsx(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 = useMemo(() => ({
    width: tableInnerContainerWidth
  }), [tableInnerContainerWidth]);
  const emptyStateContainer = useCallback(() => _jsx(Box, {
    sx: innerWidthStyle,
    children: emptyState
  }), [innerWidthStyle, emptyState]);
  useEffect(() => {
    if (enableVirtualization) {
      shouldUpdateScroll.current = true;
    }
  }, [enableVirtualization, pagination]);
  useEffect(() => {
    if (shouldUpdateScroll.current && tableContentRef.current && typeof tableInnerContainerRef.current?.scrollTo !== "undefined") {
      tableInnerContainerRef.current?.scrollTo(0, tableContentRef.current.clientHeight);
      shouldUpdateScroll.current = false;
    }
  }, [data]);
  const shouldDisplayRowActions = 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 = useMaterialReactTable({
    data: !isEmpty && !isNoResults ? data : [],
    columns,
    getRowId,
    state: {
      sorting: tableState.columnSorting,
      columnVisibility: tableState.columnVisibility,
      isLoading,
      rowSelection,
      columnOrder
    },
    icons: {
      ArrowDownwardIcon: ArrowDownIcon,
      DragHandleIcon: DragIndicatorIcon,
      SyncAltIcon: ArrowUnsortedIcon,
      ExpandMoreIcon: ChevronDownIcon
    },
    ...dataTableImmutableSettings,
    displayColumnDefOptions: {
      ...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: _jsxs(Box, {
            sx: {
              display: "flex",
              visibility: "hidden"
            },
            children: [tableLayoutOptions.rowActionButtons && tableLayoutOptions.rowActionButtons(), (hasRowReordering === true && onReorderRows || tableLayoutOptions.rowActionMenuItems) && _jsx(Box, {
              children: _jsx(Button, {
                ariaLabel: t("table.moreactions.arialabel"),
                endIcon: _jsx(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 _jsx(ScrollableTableContainer, {
    isScrollableEnd: !isTableContainerScrolledToEnd,
    isScrollableStart: !isTableContainerScrolledToStart,
    odysseyDesignTokens: odysseyDesignTokens,
    ref: tableOuterContainerRef,
    children: _jsx(MRT_TableContainer, {
      table: dataTable
    })
  });
};
const MemoizedTableLayoutContent = memo(TableLayoutContent);
MemoizedTableLayoutContent.displayName = "TableLayoutContent";
export { MemoizedTableLayoutContent as TableLayoutContent };
//# sourceMappingURL=TableLayoutContent.js.map