/*!
 * 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 { memo, useCallback, useEffect, useMemo, useState } from "react";
import { Box } from "../../Box.js";
import { MenuButton } from "../../Buttons/MenuButton.js";
import { Callout } from "../../Callout.js";
import { createUniqueId } from "../../createUniqueId.js";
import { useRowReordering } from "../../DataTable/useRowReordering.js";
import { EmptyState } from "../../EmptyState.js";
import { useTranslation } from "../../i18n.generated/i18n.js";
import { MoreIcon } from "../../icons.generated/index.js";
import { useOdysseyDesignTokens } from "../../OdysseyDesignTokensContext.js";
import { Pagination } from "../../Pagination/Pagination.js";
import { usePagination } from "../../Pagination/usePagination.js";
import { Typography } from "../../Typography.js";
import { DataFilters } from "../DataFilters.js";
import { BulkActionsMenu } from "./BulkActionsMenu.js";
import { CardLayoutContent } from "./CardLayoutContent.js";
import { availableLayouts as allAvailableLayouts, densityValues } from "./constants.js";
import { fetchData } from "./fetchData.js";
import { LayoutSwitcher } from "./LayoutSwitcher.js";
import { TableLayoutContent } from "./TableLayoutContent.js";
import { TableSettings } from "./TableSettings.js";
import { useFilterConversion } from "./useFilterConversion.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const StyledDataViewContainer = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  flexDirection: "column",
  gap: odysseyDesignTokens.Spacing4
}));
const StyledBulkActionsContainer = styled("div")(() => ({
  display: "flex",
  justifyContent: "space-between"
}));
const StyledAdditionalActionsContainer = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  justifyContent: "flex-end",
  gap: odysseyDesignTokens.Spacing2
}));
const StyledAdditionalActionsInner = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  alignItems: "center",
  gap: odysseyDesignTokens.Spacing2
}));
const StyledMetaTextContainer = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  marginInlineEnd: odysseyDesignTokens.Spacing2
}));
const DataView = ({
  additionalActionButton,
  additionalActionMenuItems,
  availableLayouts = allAvailableLayouts,
  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 = useOdysseyDesignTokens();
  const {
    t
  } = useTranslation();
  const [currentLayout, setCurrentLayout] = useState(initialLayout ?? availableLayouts[0]);
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(isLoadingProp ?? true);
  const [isEmpty, setIsEmpty] = useState(isEmptyProp ?? true);
  const [isNoResults, setIsNoResults] = useState(isNoResultsProp ?? false);
  const [errorMessage, setErrorMessage] = useState(errorMessageProp);
  const [search, setSearch] = useState("");
  const [initialFilters, setInitialFilters] = useState(filtersProp);
  const [filters, setFilters] = useState(filtersProp);
  const [draggingRow, setDraggingRow] = useState();
  const [rowSelection, setRowSelection] = useState({});
  useEffect(() => {
    onChangeRowSelection?.(rowSelection);
  }, [rowSelection, onChangeRowSelection]);
  useEffect(() => {
    onRowSelectionChange?.(rowSelection);
  }, [rowSelection, onRowSelectionChange]);
  const [pagination, setPagination] = useState({
    pageIndex: currentPage,
    pageSize: resultsPerPage
  });
  const [tableState, setTableState] = useState({
    columnSorting: [],
    columnVisibility: {},
    rowDensity: tableLayoutOptions?.initialDensity ?? densityValues[0]
  });
  const shouldShowFilters = hasSearch || hasFilters || additionalActionButton || additionalActionMenuItems;
  const availableFilters = useFilterConversion({
    filters: filters,
    columns: tableLayoutOptions?.columns
  });
  useEffect(() => {
    if (!initialFilters && availableFilters) {
      setInitialFilters(availableFilters);
    }
  }, [availableFilters, initialFilters]);
  const dataQueryParams = useMemo(() => ({
    page: pagination.pageIndex,
    resultsPerPage: pagination.pageSize,
    search,
    filters: availableFilters,
    sort: tableState?.columnSorting
  }), [pagination.pageIndex, pagination.pageSize, search, availableFilters, tableState?.columnSorting]);
  const getRowId = useCallback((row, index, parentRow) => {
    if (getRowIdProp) {
      return getRowIdProp(row, index, parentRow);
    }
    if (row.id) {
      return row.id;
    }
    return createUniqueId();
  }, [getRowIdProp]);
  useEffect(() => {
    setPagination({
      pageIndex: currentPage,
      pageSize: resultsPerPage
    });
  }, [currentPage, resultsPerPage]);
  useEffect(() => {
    setPagination(prev => ({
      pageIndex: 1,
      pageSize: paginationType == "loadMore" ? resultsPerPage : prev.pageSize
    }));
  }, [filters, paginationType, resultsPerPage, search]);
  useEffect(() => {
    onPaginationChange?.(pagination);
  }, [onPaginationChange, pagination]);
  useEffect(() => {
    fetchData({
      dataQueryParams,
      errorMessageProp,
      getData,
      setData,
      setErrorMessage,
      setIsLoading: isLoadingProp ? undefined : setIsLoading
    });
  }, [dataQueryParams, errorMessageProp, getData, isLoadingProp]);
  useEffect(() => {
    setIsEmpty(pagination.pageIndex === currentPage && pagination.pageSize === resultsPerPage && search === "" && (!hasFilters || filters === initialFilters) && data.length === 0);
  }, [currentPage, data, filters, hasFilters, initialFilters, pagination, resultsPerPage, search]);
  useEffect(() => {
    setIsLoading(prevValue => isLoadingProp ?? prevValue);
  }, [isLoadingProp]);
  useEffect(() => {
    setIsEmpty(prevValue => isEmptyProp ?? prevValue);
  }, [isEmptyProp]);
  useEffect(() => {
    setIsNoResults(prevValue => isNoResultsProp ?? prevValue);
  }, [isNoResultsProp]);
  const emptyState = useMemo(() => {
    const noResultsInnerContent = noResultsPlaceholder || _jsx(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 = useMemo(() => {
    return (metaText || currentLayout === "table" && tableLayoutOptions || availableLayouts.length > 1 || additionalActionButton || additionalActionMenuItems) && _jsxs(StyledAdditionalActionsInner, {
      odysseyDesignTokens: odysseyDesignTokens,
      children: [metaText && _jsx(StyledMetaTextContainer, {
        odysseyDesignTokens: odysseyDesignTokens,
        children: _jsx(Typography, {
          color: "textSecondary",
          children: metaText
        })
      }), currentLayout === "table" && tableLayoutOptions && _jsx(TableSettings, {
        setTableState: setTableState,
        tableLayoutOptions: tableLayoutOptions,
        tableState: tableState
      }), availableLayouts.length > 1 && _jsx(LayoutSwitcher, {
        availableLayouts: availableLayouts,
        currentLayout: currentLayout,
        setCurrentLayout: setCurrentLayout
      }), additionalActionButton, additionalActionMenuItems && _jsx(MenuButton, {
        ariaLabel: t("table.moreactions.arialabel"),
        buttonVariant: "secondary",
        endIcon: _jsx(MoreIcon, {}),
        menuAlignment: "right",
        children: additionalActionMenuItems
      })]
    });
  }, [additionalActionButton, additionalActionMenuItems, availableLayouts, currentLayout, metaText, odysseyDesignTokens, tableLayoutOptions, tableState, t]);
  const enableVirtualization = useMemo(() => enableVirtualizationProp ?? paginationType === "loadMore", [enableVirtualizationProp, paginationType]);
  const {
    lastRow: lastRowOnPage
  } = usePagination({
    currentRowsCount: data.length,
    pageIndex: pagination.pageIndex,
    pageSize: pagination.pageSize,
    totalRows
  });
  const rowReorderingUtilities = useRowReordering({
    totalRows,
    onReorderRows,
    data,
    setData,
    draggingRow,
    setDraggingRow,
    resultsPerPage: pagination.pageSize,
    page: pagination.pageIndex
  });
  return _jsxs(StyledDataViewContainer, {
    odysseyDesignTokens: odysseyDesignTokens,
    children: [errorMessage && _jsx(Box, {
      children: _jsx(Callout, {
        severity: "error",
        text: errorMessage
      })
    }), shouldShowFilters && _jsx(DataFilters, {
      additionalActions: additionalActions,
      filters: hasFilters ? availableFilters : undefined,
      hasSearchSubmitButton: hasSearchSubmitButton,
      isDisabled: isEmpty,
      onChangeFilters: hasFilters ? setFilters : undefined,
      onChangeSearch: hasSearch ? setSearch : undefined,
      searchDelayTime: searchDelayTime
    }), (bulkActionMenuItems || hasRowSelection) && _jsxs(StyledBulkActionsContainer, {
      children: [_jsx(BulkActionsMenu, {
        data: data,
        menuItems: bulkActionMenuItems,
        rowSelection: rowSelection,
        setRowSelection: setRowSelection
      }), !shouldShowFilters && additionalActions]
    }), !shouldShowFilters && !bulkActionMenuItems && !hasRowSelection && additionalActions && _jsx(StyledAdditionalActionsContainer, {
      odysseyDesignTokens: odysseyDesignTokens,
      children: additionalActions
    }), currentLayout === "table" && tableLayoutOptions && _jsx(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 && _jsx(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 && _jsx(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 = memo(DataView);
MemoizedDataView.displayName = "DataView";
export { MemoizedDataView as DataView };
//# sourceMappingURL=DataView.js.map