import _InputBase from "@mui/material/InputBase";
/*!
 * 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 { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Box } from "../Box.js";
import { Button } from "../Buttons/Button.js";
import { useTranslation } from "../i18n.generated/i18n.js";
import { ArrowLeftIcon, ArrowRightIcon } from "../icons.generated/index.js";
import { useOdysseyDesignTokens } from "../OdysseyDesignTokensContext.js";
import { Paragraph } from "../Typography.js";
import { usePagination } from "./usePagination.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const PaginationContainer = styled("nav")({
  display: "flex",
  justifyContent: "space-between"
});
const PaginationSegment = styled("div", {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  display: "flex",
  alignItems: "center",
  gap: odysseyDesignTokens.Spacing4,
  "& > div": {
    display: "flex",
    alignItems: "center",
    gap: odysseyDesignTokens.Spacing2
  }
}));
const PaginationInput = styled(_InputBase, {
  shouldForwardProp: prop => prop !== "odysseyDesignTokens"
})(({
  odysseyDesignTokens
}) => ({
  borderColor: odysseyDesignTokens.HueNeutral200,
  borderRadius: odysseyDesignTokens.BorderRadiusTight,
  height: odysseyDesignTokens.Spacing6,
  width: "4.5714285714rem",
  "&:hover": {
    borderColor: odysseyDesignTokens.HueNeutral400
  },
  "&.Mui-focused:hover": {
    borderColor: odysseyDesignTokens.PalettePrimaryMain
  }
}));
const PaginationButtonContainer = styled("div")({
  "& > *": {
    marginInlineStart: `0 !important`
  }
});
const Pagination = ({
  currentPageLabel: currentPageLabelProp,
  currentRowsCount,
  hasPageInput = true,
  hasRowCountInput = true,
  hasRowCountLabel = true,
  isDisabled,
  isMoreDisabled,
  lastRow,
  loadMoreLabel: loadMoreLabelProp,
  maxPageIndex,
  maxPageSize,
  nextLabel: nextLabelProp,
  onPaginationChange: onPaginationChangeProp,
  pageIndex,
  pageSize,
  previousLabel: previousLabelProp,
  rowsPerPageLabel: rowsPerPageLabelProp,
  totalRows,
  variant
}) => {
  const odysseyDesignTokens = useOdysseyDesignTokens();
  const {
    t
  } = useTranslation();
  const [page, setPage] = useState(pageIndex);
  const [rowsPerPage, setRowsPerPage] = useState(pageSize);
  const initialRowsPerPage = useRef(pageSize);
  const currentPageLabel = currentPageLabelProp ?? t("pagination.page");
  const loadMoreLabel = loadMoreLabelProp ?? t("pagination.loadmore");
  const nextLabel = nextLabelProp ?? t("pagination.next");
  const previousLabel = previousLabelProp ?? t("pagination.previous");
  const rowsPerPageLabel = rowsPerPageLabelProp ?? t("pagination.rowsperpage");
  useEffect(() => {
    setPage(pageIndex);
    setRowsPerPage(pageSize);
  }, [pageIndex, pageSize]);
  const onPaginationChange = useCallback(({
    pageIndex,
    pageSize
  }) => {
    onPaginationChangeProp({
      pageIndex,
      pageSize
    });
  }, [onPaginationChangeProp]);
  const {
    totalRowsLabel
  } = usePagination({
    pageIndex,
    pageSize,
    currentRowsCount: currentRowsCount || 0,
    totalRows
  });
  const handlePaginationChange = useCallback(() => {
    let updatedPage = page;
    let updatedRowsPerPage = rowsPerPage;
    if (totalRows) {
      const maxPageIndex = Math.ceil(totalRows / updatedRowsPerPage);
      if (updatedRowsPerPage > totalRows) {
        updatedRowsPerPage = totalRows;
      }
      if (updatedPage > maxPageIndex) {
        updatedPage = maxPageIndex;
      } else if (updatedPage < 1) {
        updatedPage = 1;
      }
    }
    onPaginationChange({
      pageIndex: updatedPage,
      pageSize: updatedRowsPerPage
    });
  }, [page, rowsPerPage, onPaginationChange, totalRows]);
  const handlePageSubmit = useCallback(event => {
    if (event.key === "Enter") {
      onPaginationChange({
        pageIndex: Number(event.currentTarget.value),
        pageSize: rowsPerPage
      });
    }
  }, [rowsPerPage, onPaginationChange]);
  const handleRowsPerPageSubmit = useCallback(event => {
    if (event.key === "Enter") {
      onPaginationChange({
        pageIndex: page,
        pageSize: Number(event.currentTarget.value)
      });
    }
  }, [page, onPaginationChange]);
  const setPageFromEvent = useCallback(event => {
    const value = maxPageIndex ? Math.min(Number(event.target.value), maxPageIndex) : Number(event.target.value);
    setPage(Math.max(1, value));
  }, [setPage, maxPageIndex]);
  const setRowsPerPageFromEvent = useCallback(event => {
    const value = maxPageSize ? Math.min(Number(event.target.value), maxPageSize) : Number(event.target.value);
    setRowsPerPage(Math.max(1, value));
  }, [setRowsPerPage, maxPageSize]);
  const handleLoadMore = useCallback(() => {
    onPaginationChange({
      pageIndex: 1,
      pageSize: rowsPerPage + initialRowsPerPage.current
    });
  }, [rowsPerPage, onPaginationChange]);
  const handleNextButton = useCallback(() => {
    onPaginationChange({
      pageIndex: page + 1,
      pageSize: rowsPerPage
    });
  }, [onPaginationChange, page, rowsPerPage]);
  const handlePreviousButton = useCallback(() => {
    onPaginationChange({
      pageIndex: page - 1,
      pageSize: rowsPerPage
    });
  }, [onPaginationChange, page, rowsPerPage]);
  const loadMoreIsDisabled = useMemo(() => {
    return isMoreDisabled || (totalRows ? rowsPerPage >= totalRows : false);
  }, [isMoreDisabled, rowsPerPage, totalRows]);
  const nextButtonDisabled = useMemo(() => isMoreDisabled || lastRow && (totalRows ? lastRow >= totalRows : false) || isDisabled, [isMoreDisabled, totalRows, lastRow, isDisabled]);
  const previousButtonDisabled = useMemo(() => pageIndex <= 1 || isDisabled, [pageIndex, isDisabled]);
  const rowsPerPageInputProps = useMemo(() => ({
    "aria-label": rowsPerPageLabel,
    max: maxPageSize || totalRows
  }), [maxPageSize, rowsPerPageLabel, totalRows]);
  const currentPageInputProps = useMemo(() => ({
    "aria-label": currentPageLabel,
    max: maxPageIndex
  }), [currentPageLabel, maxPageIndex]);
  return variant === "paged" ? _jsxs(PaginationContainer, {
    "aria-label": t("pagination.label"),
    children: [_jsxs(PaginationSegment, {
      odysseyDesignTokens: odysseyDesignTokens,
      children: [hasRowCountInput && _jsxs(Box, {
        children: [_jsx(Paragraph, {
          color: "textSecondary",
          component: "span",
          children: rowsPerPageLabel
        }), _jsx(PaginationInput, {
          disabled: isDisabled,
          inputProps: rowsPerPageInputProps,
          odysseyDesignTokens: odysseyDesignTokens,
          onBlur: handlePaginationChange,
          onChange: setRowsPerPageFromEvent,
          onKeyDown: handleRowsPerPageSubmit,
          type: "number",
          value: rowsPerPage
        })]
      }), hasRowCountLabel && _jsx(Paragraph, {
        color: "textSecondary",
        component: "span",
        children: totalRowsLabel
      })]
    }), _jsxs(PaginationSegment, {
      odysseyDesignTokens: odysseyDesignTokens,
      children: [totalRows && hasPageInput && _jsxs(Box, {
        children: [_jsx(Paragraph, {
          color: "textSecondary",
          component: "span",
          children: currentPageLabel
        }), _jsx(PaginationInput, {
          disabled: isDisabled,
          inputProps: currentPageInputProps,
          odysseyDesignTokens: odysseyDesignTokens,
          onBlur: handlePaginationChange,
          onChange: setPageFromEvent,
          onKeyDown: handlePageSubmit,
          type: "number",
          value: page
        })]
      }), _jsxs(PaginationButtonContainer, {
        children: [_jsx(Button, {
          ariaLabel: previousLabel,
          isDisabled: previousButtonDisabled,
          onClick: handlePreviousButton,
          size: "small",
          startIcon: _jsx(ArrowLeftIcon, {}),
          variant: "floating"
        }), _jsx(Button, {
          ariaLabel: nextLabel,
          endIcon: _jsx(ArrowRightIcon, {}),
          isDisabled: nextButtonDisabled,
          onClick: handleNextButton,
          size: "small",
          variant: "floating"
        })]
      })]
    })]
  }) : _jsx(Button, {
    isDisabled: loadMoreIsDisabled,
    label: loadMoreLabel,
    onClick: handleLoadMore,
    variant: "secondary"
  });
};
const MemoizedPagination = memo(Pagination);
MemoizedPagination.displayName = "Pagination";
export { MemoizedPagination as Pagination };
//# sourceMappingURL=Pagination.js.map