"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DataView = void 0;
var _styled = _interopRequireDefault(require("@emotion/styled"));
var _react = require("react");
var _Box = require("../../Box.cjs");
var _MenuButton = require("../../Buttons/MenuButton.cjs");
var _Callout = require("../../Callout.cjs");
var _createUniqueId = require("../../createUniqueId.cjs");
var _useRowReordering = require("../../DataTable/useRowReordering.cjs");
var _EmptyState = require("../../EmptyState.cjs");
var _i18n = require("../../i18n.generated/i18n.cjs");
var _index = require("../../icons.generated/index.cjs");
var _OdysseyDesignTokensContext = require("../../OdysseyDesignTokensContext.cjs");
var _Pagination = require("../../Pagination/Pagination.cjs");
var _usePagination = require("../../Pagination/usePagination.cjs");
var _Typography = require("../../Typography.cjs");
var _DataFilters = require("../DataFilters.cjs");
var _BulkActionsMenu = require("./BulkActionsMenu.cjs");
var _CardLayoutContent = require("./CardLayoutContent.cjs");
var _constants = require("./constants.cjs");
var _fetchData = require("./fetchData.cjs");
var _LayoutSwitcher = require("./LayoutSwitcher.cjs");
var _TableLayoutContent = require("./TableLayoutContent.cjs");
var _TableSettings = require("./TableSettings.cjs");
var _useFilterConversion = require("./useFilterConversion.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 StyledDataViewContainer = (0, _styled.default)("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  flexDirection: "column",
  gap: odysseyDesignTokens.Spacing4
}));
const StyledBulkActionsContainer = (0, _styled.default)("div")(() => ({
  display: "flex",
  justifyContent: "space-between"
}));
const StyledAdditionalActionsContainer = (0, _styled.default)("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  justifyContent: "flex-end",
  gap: odysseyDesignTokens.Spacing2
}));
const StyledAdditionalActionsInner = (0, _styled.default)("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  alignItems: "center",
  gap: odysseyDesignTokens.Spacing2
}));
const StyledMetaTextContainer = (0, _styled.default)("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  marginInlineEnd: odysseyDesignTokens.Spacing2
}));
const DataView = ({
  additionalActionButton,
  additionalActionMenuItems,
  availableLayouts = _constants.availableLayouts,
  bulkActionMenuItems,
  currentPage = 1,
  emptyPlaceholder,
  enableVirtualization: enableVirtualizationProp,
  errorMessage: errorMessageProp,
  filters: filtersProp,
  getData,
  getRowId: getRowIdProp,
  hasFilters,
  hasPagination,
  hasPageInput,
  hasRowCountInput,
  hasRowCountLabel,
  hasSearch,
  hasSearchSubmitButton,
  hasRowReordering,
  hasRowSelection,
  initialLayout,
  isEmpty: isEmptyProp,
  isLoading: isLoadingProp,
  isNoResults: isNoResultsProp,
  isPaginationMoreDisabled,
  isRowReorderingDisabled,
  metaText,
  noResultsPlaceholder,
  onChangeRowSelection,
  onReorderRows,
  onRowSelectionChange,
  paginationType = "paged",
  resultsPerPage = 20,
  searchDelayTime,
  cardLayoutOptions,
  tableLayoutOptions,
  totalRows,
  maxPages,
  maxResultsPerPage,
  onPaginationChange
}) => {
  const odysseyDesignTokens = (0, _OdysseyDesignTokensContext.useOdysseyDesignTokens)();
  const {
    t
  } = (0, _i18n.useTranslation)();
  const [currentLayout, setCurrentLayout] = (0, _react.useState)(initialLayout ?? availableLayouts[0]);
  const [data, setData] = (0, _react.useState)([]);
  const [isLoading, setIsLoading] = (0, _react.useState)(isLoadingProp ?? true);
  const [isEmpty, setIsEmpty] = (0, _react.useState)(isEmptyProp ?? true);
  const [isNoResults, setIsNoResults] = (0, _react.useState)(isNoResultsProp ?? false);
  const [errorMessage, setErrorMessage] = (0, _react.useState)(errorMessageProp);
  const [search, setSearch] = (0, _react.useState)("");
  const [initialFilters, setInitialFilters] = (0, _react.useState)(filtersProp);
  const [filters, setFilters] = (0, _react.useState)(filtersProp);
  const [draggingRow, setDraggingRow] = (0, _react.useState)();
  const [rowSelection, setRowSelection] = (0, _react.useState)({});
  (0, _react.useEffect)(() => {
    onChangeRowSelection?.(rowSelection);
  }, [rowSelection, onChangeRowSelection]);
  (0, _react.useEffect)(() => {
    onRowSelectionChange?.(rowSelection);
  }, [rowSelection, onRowSelectionChange]);
  const [pagination, setPagination] = (0, _react.useState)({
    pageIndex: currentPage,
    pageSize: resultsPerPage
  });
  const [tableState, setTableState] = (0, _react.useState)({
    columnSorting: [],
    columnVisibility: {},
    rowDensity: tableLayoutOptions?.initialDensity ?? _constants.densityValues[0]
  });
  const shouldShowFilters = hasSearch || hasFilters || additionalActionButton || additionalActionMenuItems;
  const availableFilters = (0, _useFilterConversion.useFilterConversion)({
    filters: filters,
    columns: tableLayoutOptions?.columns
  });
  (0, _react.useEffect)(() => {
    if (!initialFilters && availableFilters) {
      setInitialFilters(availableFilters);
    }
  }, [availableFilters, initialFilters]);
  const dataQueryParams = (0, _react.useMemo)(() => ({
    page: pagination.pageIndex,
    resultsPerPage: pagination.pageSize,
    search,
    filters: availableFilters,
    sort: tableState?.columnSorting
  }), [pagination.pageIndex, pagination.pageSize, search, availableFilters, tableState?.columnSorting]);
  const getRowId = (0, _react.useCallback)((row, index, parentRow) => {
    if (getRowIdProp) {
      return getRowIdProp(row, index, parentRow);
    }
    if (row.id) {
      return row.id;
    }
    return (0, _createUniqueId.createUniqueId)();
  }, [getRowIdProp]);
  (0, _react.useEffect)(() => {
    setPagination({
      pageIndex: currentPage,
      pageSize: resultsPerPage
    });
  }, [currentPage, resultsPerPage]);
  (0, _react.useEffect)(() => {
    setPagination(prev => ({
      pageIndex: 1,
      pageSize: paginationType == "loadMore" ? resultsPerPage : prev.pageSize
    }));
  }, [filters, paginationType, resultsPerPage, search]);
  (0, _react.useEffect)(() => {
    onPaginationChange?.(pagination);
  }, [onPaginationChange, pagination]);
  (0, _react.useEffect)(() => {
    (0, _fetchData.fetchData)({
      dataQueryParams,
      errorMessageProp,
      getData,
      setData,
      setErrorMessage,
      setIsLoading: isLoadingProp ? undefined : setIsLoading
    });
  }, [dataQueryParams, errorMessageProp, getData, isLoadingProp]);
  (0, _react.useEffect)(() => {
    setIsEmpty(pagination.pageIndex === currentPage && pagination.pageSize === resultsPerPage && search === "" && (!hasFilters || filters === initialFilters) && data.length === 0);
  }, [currentPage, data, filters, hasFilters, initialFilters, pagination, resultsPerPage, search]);
  (0, _react.useEffect)(() => {
    setIsLoading(prevValue => isLoadingProp ?? prevValue);
  }, [isLoadingProp]);
  (0, _react.useEffect)(() => {
    setIsEmpty(prevValue => isEmptyProp ?? prevValue);
  }, [isEmptyProp]);
  (0, _react.useEffect)(() => {
    setIsNoResults(prevValue => isNoResultsProp ?? prevValue);
  }, [isNoResultsProp]);
  const emptyState = (0, _react.useMemo)(() => {
    const noResultsInnerContent = noResultsPlaceholder || (0, _jsxRuntime.jsx)(_EmptyState.EmptyState, {
      description: t("table.noresults.text"),
      heading: t("table.noresults.heading")
    });
    if (isEmpty) {
      return emptyPlaceholder || noResultsInnerContent;
    }
    if (isNoResults) {
      return noResultsInnerContent;
    }
    return;
  }, [noResultsPlaceholder, t, isEmpty, isNoResults, emptyPlaceholder]);
  const additionalActions = (0, _react.useMemo)(() => {
    return (metaText || currentLayout === "table" && tableLayoutOptions || availableLayouts.length > 1 || additionalActionButton || additionalActionMenuItems) && (0, _jsxRuntime.jsxs)(StyledAdditionalActionsInner, {
      odysseyDesignTokens: odysseyDesignTokens,
      children: [metaText && (0, _jsxRuntime.jsx)(StyledMetaTextContainer, {
        odysseyDesignTokens: odysseyDesignTokens,
        children: (0, _jsxRuntime.jsx)(_Typography.Typography, {
          color: "textSecondary",
          children: metaText
        })
      }), currentLayout === "table" && tableLayoutOptions && (0, _jsxRuntime.jsx)(_TableSettings.TableSettings, {
        setTableState: setTableState,
        tableLayoutOptions: tableLayoutOptions,
        tableState: tableState
      }), availableLayouts.length > 1 && (0, _jsxRuntime.jsx)(_LayoutSwitcher.LayoutSwitcher, {
        availableLayouts: availableLayouts,
        currentLayout: currentLayout,
        setCurrentLayout: setCurrentLayout
      }), additionalActionButton, additionalActionMenuItems && (0, _jsxRuntime.jsx)(_MenuButton.MenuButton, {
        ariaLabel: t("table.moreactions.arialabel"),
        buttonVariant: "secondary",
        endIcon: (0, _jsxRuntime.jsx)(_index.MoreIcon, {}),
        menuAlignment: "right",
        children: additionalActionMenuItems
      })]
    });
  }, [additionalActionButton, additionalActionMenuItems, availableLayouts, currentLayout, metaText, odysseyDesignTokens, tableLayoutOptions, tableState, t]);
  const enableVirtualization = (0, _react.useMemo)(() => enableVirtualizationProp ?? paginationType === "loadMore", [enableVirtualizationProp, paginationType]);
  const {
    lastRow: lastRowOnPage
  } = (0, _usePagination.usePagination)({
    currentRowsCount: data.length,
    pageIndex: pagination.pageIndex,
    pageSize: pagination.pageSize,
    totalRows
  });
  const rowReorderingUtilities = (0, _useRowReordering.useRowReordering)({
    totalRows,
    onReorderRows,
    data,
    setData,
    draggingRow,
    setDraggingRow,
    resultsPerPage: pagination.pageSize,
    page: pagination.pageIndex
  });
  return (0, _jsxRuntime.jsxs)(StyledDataViewContainer, {
    odysseyDesignTokens: odysseyDesignTokens,
    children: [errorMessage && (0, _jsxRuntime.jsx)(_Box.Box, {
      children: (0, _jsxRuntime.jsx)(_Callout.Callout, {
        severity: "error",
        text: errorMessage
      })
    }), shouldShowFilters && (0, _jsxRuntime.jsx)(_DataFilters.DataFilters, {
      additionalActions: additionalActions,
      filters: hasFilters ? availableFilters : undefined,
      hasSearchSubmitButton: hasSearchSubmitButton,
      isDisabled: isEmpty,
      onChangeFilters: hasFilters ? setFilters : undefined,
      onChangeSearch: hasSearch ? setSearch : undefined,
      searchDelayTime: searchDelayTime
    }), (bulkActionMenuItems || hasRowSelection) && (0, _jsxRuntime.jsxs)(StyledBulkActionsContainer, {
      children: [(0, _jsxRuntime.jsx)(_BulkActionsMenu.BulkActionsMenu, {
        data: data,
        menuItems: bulkActionMenuItems,
        rowSelection: rowSelection,
        setRowSelection: setRowSelection
      }), !shouldShowFilters && additionalActions]
    }), !shouldShowFilters && !bulkActionMenuItems && !hasRowSelection && additionalActions && (0, _jsxRuntime.jsx)(StyledAdditionalActionsContainer, {
      odysseyDesignTokens: odysseyDesignTokens,
      children: additionalActions
    }), currentLayout === "table" && tableLayoutOptions && (0, _jsxRuntime.jsx)(_TableLayoutContent.TableLayoutContent, {
      columns: tableLayoutOptions.columns,
      data: data,
      draggingRow: draggingRow,
      emptyState: emptyState,
      enableVirtualization: enableVirtualization,
      getRowId: getRowIdProp || getRowId,
      hasRowReordering: hasRowReordering,
      hasRowSelection: hasRowSelection,
      isEmpty: isEmpty,
      isLoading: isLoading,
      isNoResults: isNoResults,
      isRowReorderingDisabled: isRowReorderingDisabled,
      onReorderRows: onReorderRows,
      pagination: pagination,
      rowReorderingUtilities: rowReorderingUtilities,
      rowSelection: rowSelection,
      setRowSelection: setRowSelection,
      setTableState: setTableState,
      tableLayoutOptions: tableLayoutOptions,
      tableState: tableState,
      totalRows: totalRows
    }), (currentLayout === "list" || currentLayout === "grid") && cardLayoutOptions && (0, _jsxRuntime.jsx)(_CardLayoutContent.CardLayoutContent, {
      cardLayoutOptions: cardLayoutOptions,
      currentLayout: currentLayout,
      data: data,
      draggingRow: draggingRow,
      emptyState: emptyState,
      getRowId: getRowIdProp || getRowId,
      hasRowReordering: hasRowReordering,
      hasRowSelection: hasRowSelection,
      isEmpty: isEmpty,
      isLoading: isLoading,
      isNoResults: isNoResults,
      isRowReorderingDisabled: isRowReorderingDisabled,
      onReorderRows: onReorderRows,
      pagination: pagination,
      rowReorderingUtilities: rowReorderingUtilities,
      rowSelection: rowSelection,
      setRowSelection: setRowSelection,
      totalRows: totalRows
    }), hasPagination && (0, _jsxRuntime.jsx)(_Pagination.Pagination, {
      currentPageLabel: t("pagination.page"),
      currentRowsCount: data.length,
      hasPageInput: hasPageInput,
      hasRowCountInput: hasRowCountInput,
      hasRowCountLabel: hasRowCountLabel,
      isDisabled: isEmpty,
      isMoreDisabled: isPaginationMoreDisabled,
      lastRow: lastRowOnPage,
      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 MemoizedDataView = exports.DataView = (0, _react.memo)(DataView);
MemoizedDataView.displayName = "DataView";
//# sourceMappingURL=DataView.cjs.map