/*!
 * Copyright (c) 2023-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 { Callout } from "../Callout.js";
import { EmptyState } from "../EmptyState.js";
import { useTranslation } from "../i18n.generated/i18n.js";
import { ArrowDownIcon, ArrowUnsortedIcon, ChevronDownIcon, DragIndicatorIcon, MoreIcon } from "../icons.generated/index.js";
import { DataFilters } from "../labs/DataFilters.js";
import { useOdysseyDesignTokens } from "../OdysseyDesignTokensContext.js";
import { Pagination } from "../Pagination/Pagination.js";
import { usePagination } from "../Pagination/usePagination.js";
import { densityValues } from "./constants.js";
import { DataTableRowActions } from "./DataTableRowActions.js";
import { DataTableSettings } from "./DataTableSettings.js";
import { useRowReordering } from "./useRowReordering.js";
import { useScrollIndication } from "./useScrollIndication.js";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const ScrollableTableContainer = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens" && prop !== "isScrollableStart" && prop !== "isScrollableEnd"
})(({
  odysseyDesignTokens,
  isScrollableStart,
  isScrollableEnd
}) => ({
  marginBlockEnd: odysseyDesignTokens.Spacing4,
  position: "relative",
  borderInlineStartColor: isScrollableStart ? odysseyDesignTokens.HueNeutral200 : "transparent",
  borderInlineStartStyle: "solid",
  borderInlineStartWidth: odysseyDesignTokens.BorderWidthMain,
  "::before": {
    background: "linear-gradient(-90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.33) 50%, rgba(0, 0, 0, 1) 100%)",
    content: '""',
    opacity: isScrollableStart ? "0.075" : "0",
    pointerEvents: "none",
    position: "absolute",
    top: 0,
    left: 0,
    bottom: 0,
    width: odysseyDesignTokens.Spacing6,
    zIndex: 100,
    transition: `opacity ${odysseyDesignTokens.TransitionDurationMain} ${odysseyDesignTokens.TransitionTimingMain}`
  },
  borderInlineEndColor: isScrollableEnd ? odysseyDesignTokens.HueNeutral200 : "transparent",
  borderInlineEndStyle: "solid",
  borderInlineEndWidth: odysseyDesignTokens.BorderWidthMain,
  "::after": {
    background: "linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.33) 50%, rgba(0, 0, 0, 1) 100%)",
    content: '""',
    opacity: isScrollableEnd ? "0.075" : "0",
    pointerEvents: "none",
    position: "absolute",
    top: 0,
    right: 0,
    bottom: 0,
    width: odysseyDesignTokens.Spacing6,
    transition: `opacity ${odysseyDesignTokens.TransitionDurationMain} ${odysseyDesignTokens.TransitionTimingMain}`
  }
}));
const defaultGetRowId = row => row.id;
const DataTable = ({
  additionalActionButton,
  additionalActionMenuItems,
  bulkActionMenuItems,
  columns,
  currentPage = 1,
  emptyPlaceholder,
  errorMessage: errorMessageProp,
  filters: filtersProp,
  getData,
  getRowId = defaultGetRowId,
  hasChangeableDensity,
  hasColumnResizing,
  hasColumnVisibility,
  hasFilters,
  hasPagination,
  hasRowReordering,
  hasRowSelection,
  hasSearch,
  hasSearchSubmitButton,
  hasSorting,
  initialDensity = densityValues[0],
  initialSearchValue = "",
  isPaginationMoreDisabled,
  noResultsPlaceholder,
  onChangeRowSelection,
  onReorderRows,
  paginationType = "paged",
  renderDetailPanel,
  resultsPerPage = 20,
  maxResultsPerPage,
  maxPages,
  rowActionButtons,
  rowActionMenuItems,
  searchDelayTime,
  selectedRows,
  totalRows
}) => {
  const {
    t
  } = useTranslation();
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({
    pageIndex: currentPage,
    pageSize: resultsPerPage
  });
  const [draggingRow, setDraggingRow] = useState();
  const [isTableContainerScrolledToStart, setIsTableContainerScrolledToStart] = useState(true);
  const [isTableContainerScrolledToEnd, setIsTableContainerScrolledToEnd] = useState(true);
  const [tableInnerContainerWidth, setTableInnerContainerWidth] = useState("100%");
  const tableOuterContainerRef = useRef(null);
  const tableInnerContainerRef = useRef(null);
  const tableContentRef = useRef(null);
  const [columnSorting, setColumnSorting] = useState([]);
  const [columnVisibility, setColumnVisibility] = useState();
  const [rowDensity, setRowDensity] = useState(initialDensity);
  const [search, setSearch] = useState(initialSearchValue);
  const [filters, setFilters] = useState();
  const [initialFilters, setInitialFilters] = useState();
  const [isLoading, setIsLoading] = useState(true);
  const [isEmpty, setIsEmpty] = useState();
  const [errorMessage, setErrorMessage] = useState(errorMessageProp);
  const [_rowSelection, setRowSelection] = useState({});
  const rowSelection = selectedRows || _rowSelection;
  useScrollIndication({
    tableOuterContainer: tableOuterContainerRef.current,
    tableInnerContainer: tableInnerContainerRef.current,
    setIsTableContainerScrolledToStart: setIsTableContainerScrolledToStart,
    setIsTableContainerScrolledToEnd: setIsTableContainerScrolledToEnd,
    setTableInnerContainerWidth: setTableInnerContainerWidth
  });
  const odysseyDesignTokens = useOdysseyDesignTokens();
  const {
    dragHandleStyles,
    dragHandleText,
    draggableTableBodyRowClassName,
    handleDragHandleKeyDown,
    handleDragHandleOnDragCapture,
    handleDragHandleOnDragEnd,
    resetDraggingAndHoveredRow,
    updateRowOrder
  } = useRowReordering({
    totalRows,
    onReorderRows,
    data,
    setData,
    draggingRow,
    setDraggingRow,
    resultsPerPage: pagination.pageSize,
    page: pagination.pageIndex
  });
  const rowDensityClassName = useMemo(() => {
    return rowDensity === "spacious" ? "MuiTableBody-spacious" : rowDensity === "compact" ? "MuiTableBody-compact" : "MuiTableBody-default";
  }, [rowDensity]);
  const renderRowActions = useCallback(({
    row
  }) => {
    const currentIndex = row.index + (pagination.pageIndex - 1) * pagination.pageSize;
    return _jsx(DataTableRowActions, {
      row: row,
      rowActionButtons: rowActionButtons,
      rowActionMenuItems: rowActionMenuItems,
      rowIndex: currentIndex,
      totalRows: totalRows,
      updateRowOrder: hasRowReordering && onReorderRows ? updateRowOrder : undefined
    });
  }, [pagination, rowActionButtons, rowActionMenuItems, hasRowReordering, onReorderRows, totalRows, updateRowOrder]);
  const convertFilterSelectOptions = useCallback(options => options?.map(option => typeof option === "string" ? {
    label: option,
    value: option
  } : {
    label: option.label ?? option.value,
    value: option.value ?? option.label
  }), []);
  const convertColumnToFilter = useCallback(column => column.enableColumnFilter !== false && column.accessorKey ? {
    id: column.accessorKey,
    label: column.header,
    variant: column.filterVariant,
    options: convertFilterSelectOptions(column.filterSelectOptions)
  } : null, [convertFilterSelectOptions]);
  const dataTableFilters = useMemo(() => {
    const providedFilters = filtersProp || columns;
    return providedFilters.reduce((accumulator, item) => {
      if (typeof item === "string") {
        const foundColumn = columns.find(column => column.accessorKey === item);
        if (foundColumn) {
          const filter = convertColumnToFilter(foundColumn);
          if (filter) {
            return accumulator.concat(filter);
          }
        }
      } else if ("accessorKey" in item) {
        const filter = convertColumnToFilter(item);
        if (filter) {
          return accumulator.concat(filter);
        }
      } else if ("label" in item) {
        return accumulator.concat(item);
      }
      return accumulator;
    }, []);
  }, [columns, filtersProp, convertColumnToFilter]);
  const defaultCell = useCallback(({
    cell
  }) => {
    const value = cell.getValue();
    const hasTextWrapping = cell.column.columnDef.hasTextWrapping || cell.column.columnDef.enableWrapping;
    return hasTextWrapping ? value : _jsx(Box, {
      sx: {
        whiteSpace: "nowrap",
        textOverflow: "ellipsis",
        overflow: "hidden"
      },
      children: value
    });
  }, []);
  const emptyState = useCallback(() => {
    const noResultsInnerContent = noResultsPlaceholder || _jsx(EmptyState, {
      description: t("table.noresults.text"),
      heading: t("table.noresults.heading")
    });
    const emptyStateInnerContent = emptyPlaceholder && isEmpty ? emptyPlaceholder : noResultsInnerContent;
    return _jsx(Box, {
      sx: {
        width: tableInnerContainerWidth
      },
      children: emptyStateInnerContent
    });
  }, [emptyPlaceholder, isEmpty, noResultsPlaceholder, t, tableInnerContainerWidth]);
  const columnIds = useMemo(() => {
    return columns.map(column => column.accessorKey);
  }, [columns]);
  const columnOrder = useMemo(() => ["mrt-row-drag", "mrt-row-select", "mrt-row-expand", ...columnIds, "mrt-row-actions"], [columnIds]);
  const shouldDisplayRowActions = useMemo(() => hasRowReordering === true && onReorderRows || rowActionButtons || rowActionMenuItems ? true : false, [hasRowReordering, onReorderRows, rowActionButtons, rowActionMenuItems]);
  const muiTableBodyProps = useCallback(() => ({
    className: rowDensityClassName
  }), [rowDensityClassName]);
  const muiTableBodyCellProps = useCallback(({
    column
  }) => ({
    className: column.getIsResizing() ? "isResizing" : "",
    sx: {
      overflowWrap: "anywhere"
    }
  }), []);
  const muiDetailPanelProps = useCallback(({
    row
  }) => ({
    sx: {
      paddingBlock: row.getIsExpanded() ? `${odysseyDesignTokens.Spacing3} !important` : undefined
    }
  }), [odysseyDesignTokens.Spacing3]);
  const muiTableBodyRowProps = useCallback(({
    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: `transparent !important`
        }
      })
    }
  }), [draggableTableBodyRowClassName, draggingRow?.id]);
  const muiRowDragHandleProps = useCallback(({
    table,
    row
  }) => ({
    onKeyDown: event => handleDragHandleKeyDown({
      table,
      row,
      event
    }),
    onBlur: () => resetDraggingAndHoveredRow(table),
    onDragEnd: () => handleDragHandleOnDragEnd(table),
    onDragCapture: () => handleDragHandleOnDragCapture(table),
    sx: dragHandleStyles,
    ...dragHandleText
  }), [dragHandleStyles, dragHandleText, handleDragHandleKeyDown, resetDraggingAndHoveredRow, handleDragHandleOnDragEnd, handleDragHandleOnDragCapture]);
  const muiTableHeadCellProps = useCallback(({
    column: currentColumn
  }) => ({
    className: columnSorting.find(sortedColumn => sortedColumn.id === currentColumn.id) ? "isSorted" : "isUnsorted"
  }), [columnSorting]);
  const hasColumnWithGrow = useMemo(() => columns.some(column => column.grow === true), [columns]);
  const dataTable = useMaterialReactTable({
    columns: columns,
    data: data,
    getRowId,
    state: {
      sorting: columnSorting,
      globalFilter: search,
      columnVisibility,
      isLoading,
      rowSelection,
      columnOrder
    },
    icons: {
      ArrowDownwardIcon: ArrowDownIcon,
      DragHandleIcon: DragIndicatorIcon,
      SyncAltIcon: ArrowUnsortedIcon,
      ExpandMoreIcon: ChevronDownIcon
    },
    enableColumnActions: false,
    enableColumnResizing: hasColumnResizing,
    enableDensityToggle: false,
    enableFilters: false,
    enableFullScreenToggle: false,
    enableGlobalFilter: false,
    enableHiding: false,
    enablePagination: false,
    layoutMode: "grid-no-grow",
    manualFiltering: true,
    manualSorting: true,
    muiTablePaperProps: {
      elevation: 0,
      sx: {
        overflow: "visible"
      }
    },
    selectAllMode: "all",
    displayColumnDefOptions: {
      "mrt-row-actions": {
        header: "",
        grow: true,
        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: [rowActionButtons && rowActionButtons({
              id: null
            }), (hasRowReordering && onReorderRows || rowActionMenuItems) && _jsx(Box, {
              children: _jsx(Button, {
                ariaLabel: t("table.moreactions.arialabel"),
                endIcon: _jsx(MoreIcon, {}),
                isDisabled: true,
                size: "small",
                variant: "floating"
              })
            })]
          })
        }
      },
      "mrt-row-drag": {
        header: "",
        muiTableBodyCellProps: {
          sx: {
            minWidth: 0,
            width: "auto"
          },
          className: "ods-drag-handle"
        },
        muiTableHeadCellProps: {
          sx: {
            minWidth: 0,
            width: "auto"
          },
          children: _jsx(Box, {
            sx: {
              marginInline: "-0.1rem"
            },
            children: _jsx(DragIndicatorIcon, {
              sx: {
                marginInline: 1,
                opacity: 0
              }
            })
          })
        }
      },
      "mrt-row-select": {
        muiTableHeadCellProps: {
          padding: "checkbox"
        },
        muiTableBodyCellProps: {
          padding: "checkbox"
        }
      },
      "mrt-row-expand": {
        header: ""
      }
    },
    muiTableBodyProps,
    defaultColumn: {
      Cell: defaultCell
    },
    muiTableBodyCellProps,
    enableRowOrdering: hasRowReordering && Boolean(onReorderRows),
    enableRowDragging: hasRowReordering && Boolean(onReorderRows),
    muiDetailPanelProps,
    muiTableBodyRowProps,
    muiRowDragHandleProps,
    enableRowActions: shouldDisplayRowActions,
    positionActionsColumn: "last",
    renderRowActions: ({
      row
    }) => renderRowActions({
      row
    }),
    enableRowSelection: hasRowSelection,
    onRowSelectionChange: setRowSelection,
    enableSorting: hasSorting,
    onSortingChange: setColumnSorting,
    muiTableHeadCellProps,
    enableRowVirtualization: paginationType !== "loadMore" && pagination.pageSize > 50,
    rowVirtualizerInstanceRef: useRef(null),
    rowVirtualizerOptions: {
      overscan: 4
    },
    renderEmptyRowsFallback: emptyState,
    muiTableProps: {
      ref: tableContentRef,
      className: !shouldDisplayRowActions && hasColumnResizing ? hasColumnWithGrow ? "ods-hide-spacer-column" : "ods-hide-spacer-column ods-column-grow" : ""
    },
    muiTableContainerProps: {
      ref: tableInnerContainerRef
    },
    enableExpandAll: false,
    renderDetailPanel: renderDetailPanel
  });
  const bulkActionMenuButton = useMemo(() => _jsx(_Fragment, {
    children: _jsx(MenuButton, {
      ariaLabel: "More actions",
      buttonVariant: "secondary",
      endIcon: _jsx(MoreIcon, {}),
      isDisabled: Object.keys(rowSelection).length === 0,
      children: bulkActionMenuItems?.(rowSelection)
    })
  }), [bulkActionMenuItems, rowSelection]);
  useEffect(() => {
    (async () => {
      setIsLoading(true);
      setErrorMessage(errorMessageProp);
      try {
        const incomingData = await getData?.({
          page: pagination.pageIndex,
          resultsPerPage: pagination.pageSize,
          search,
          filters,
          sort: columnSorting
        });
        setData(incomingData);
      } catch (error) {
        setErrorMessage(typeof error === "string" ? error : t("table.error"));
      } finally {
        setIsLoading(false);
      }
    })();
  }, [columnSorting, errorMessageProp, filters, getData, pagination, search, t]);
  useEffect(() => {
    if (!initialFilters && filters) {
      setInitialFilters(filters);
    }
    setIsEmpty(pagination.pageIndex === currentPage && pagination.pageSize === resultsPerPage && search === "" && filters === initialFilters && data.length === 0);
  }, [filters, pagination, search, data, currentPage, initialFilters, resultsPerPage]);
  useEffect(() => {
    setPagination(prev => ({
      pageIndex: 1,
      pageSize: prev.pageSize
    }));
  }, [filters, search]);
  useEffect(() => {
    onChangeRowSelection?.(rowSelection);
  }, [rowSelection, onChangeRowSelection]);
  const {
    lastRow
  } = usePagination({
    currentRowsCount: data.length,
    pageIndex: pagination.pageIndex,
    pageSize: pagination.pageSize,
    totalRows
  });
  return _jsxs(_Fragment, {
    children: [(hasSearch || hasFilters || hasChangeableDensity || hasColumnVisibility || bulkActionMenuItems || additionalActionButton || additionalActionMenuItems) && _jsx(Box, {
      sx: {
        marginBottom: 5
      },
      children: _jsx(DataFilters, {
        additionalActions: _jsxs(_Fragment, {
          children: [_jsx(DataTableSettings, {
            columns: columns,
            columnVisibility: columnVisibility,
            hasChangeableDensity: hasChangeableDensity,
            hasColumnVisibility: hasColumnVisibility,
            rowDensity: rowDensity,
            setColumnVisibility: setColumnVisibility,
            setRowDensity: setRowDensity
          }), bulkActionMenuItems && bulkActionMenuButton, additionalActionButton, additionalActionMenuItems && _jsx(MenuButton, {
            ariaLabel: t("table.moreactions.arialabel"),
            buttonVariant: "secondary",
            endIcon: _jsx(MoreIcon, {}),
            menuAlignment: "right",
            children: additionalActionMenuItems
          })]
        }),
        defaultSearchTerm: initialSearchValue,
        filters: hasFilters ? dataTableFilters : undefined,
        hasSearchSubmitButton: hasSearchSubmitButton,
        isDisabled: isEmpty,
        onChangeFilters: hasFilters ? setFilters : undefined,
        onChangeSearch: hasSearch ? setSearch : undefined,
        searchDelayTime: searchDelayTime
      })
    }), errorMessage && _jsx(Box, {
      sx: {
        marginBlockEnd: 2
      },
      children: _jsx(Callout, {
        severity: "error",
        text: errorMessage
      })
    }), _jsx(ScrollableTableContainer, {
      isScrollableEnd: !isTableContainerScrolledToEnd,
      isScrollableStart: !isTableContainerScrolledToStart,
      odysseyDesignTokens: odysseyDesignTokens,
      ref: tableOuterContainerRef,
      children: _jsx(MRT_TableContainer, {
        table: dataTable
      })
    }), hasPagination && _jsx(Pagination, {
      currentPageLabel: t("pagination.page"),
      currentRowsCount: data.length,
      isDisabled: isEmpty,
      isMoreDisabled: isPaginationMoreDisabled,
      lastRow: lastRow,
      loadMoreLabel: t("pagination.loadmore"),
      maxPageIndex: maxPages,
      maxPageSize: maxResultsPerPage,
      nextLabel: t("pagination.next"),
      onPaginationChange: setPagination,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      previousLabel: t("pagination.previous"),
      rowsPerPageLabel: t("pagination.rowsperpage"),
      totalRows: totalRows,
      variant: paginationType
    })]
  });
};
const MemoizedDataTable = memo(DataTable);
MemoizedDataTable.displayName = "DataTable";
export { MemoizedDataTable as DataTable };
//# sourceMappingURL=DataTable.js.map