import React, { memo, useMemo, useState, useEffect } from 'react';
import uniqueId from 'lodash-es/uniqueId';
import { faChevronLeft } from '@fortawesome/free-solid-svg-icons/faChevronLeft';
import { faChevronRight } from '@fortawesome/free-solid-svg-icons/faChevronRight';
import { PagesButtons } from './pages-buttons';
import { ACCENT_TYPES, Button } from '../button';
import { DropdownMenu } from '../dropdown-menu';
import { TruncateWithTooltip } from '../truncate-with-tooltip';
import { Skeleton, SKELETON_TYPES } from '../skeleton';
import { useTranslation } from '../hooks/use-translation';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * New Pagination component to be used with new table component and likely in other places where pagination is needed
 * Designed for UXR only UI.
 * @midnight-gray-supported
 * @alpine-light-supported
 * @uxr-only-supported
 */
function PaginationNew({
  selectedPage,
  total,
  totalLimit,
  isExceededTotalLimit = !!totalLimit && total >= totalLimit,
  nextPage,
  itemsPerPage,
  pageSizeOptions = [10, 20, 50],
  onPageSelect,
  onItemsPerPageChange,
  isLoading = false,
  nextBtnText: nextBtnTextParams,
  previousBtnText: previousBtnTextParams,
  paginationGroupText,
  getSelectedPageSizeText,
  getPaginationSummaryText
}) {
  const {
    t
  } = useTranslation();
  const nextBtnText = nextBtnTextParams ?? t('Next page');
  const previousBtnText = previousBtnTextParams ?? t('Previous page');
  useEffect(() => {
    if (totalLimit && nextPage === undefined && process.env.NODE_ENV === 'development') {
      // eslint-disable-next-line no-console
      console.error('[PaginationNew] PaginationNew must be used with defined nextPage if totalLimit is used');
    }
  }, []);
  const pageSizeOpts = useMemo(() => {
    if (total === 0) {
      return [];
    }
    const filteredSizes = pageSizeOptions.filter(option => option < total);
    if (filteredSizes.length < pageSizeOptions.length) {
      return [...filteredSizes, total];
    }
    return pageSizeOptions;
  }, [pageSizeOptions, total]);
  const itemsPerPageOptions = useMemo(() => pageSizeOpts.map(item => ({
    key: item,
    title: item,
    testId: `page-size-option-${item}`
  })), [pageSizeOpts]);
  const numberOfPages = useMemo(() => {
    if (isExceededTotalLimit) {
      if (!nextPage) {
        return selectedPage + 1;
      }
      return selectedPage >= Math.ceil(totalLimit / itemsPerPage) ? selectedPage + 1 : Math.ceil(totalLimit / itemsPerPage);
    }
    return Math.ceil(total / itemsPerPage);
  }, [itemsPerPage, total, totalLimit, nextPage, selectedPage, isExceededTotalLimit]);
  const isNextDisabled = isExceededTotalLimit ? !nextPage : selectedPage + 1 >= numberOfPages;
  const [perPageTriggerId] = useState(`pagination-items-per-page-trigger-${uniqueId()}`);
  const getDefaultPaginationSummaryText = () => {
    const start = total === 0 ? 0 : itemsPerPage * selectedPage + 1;
    const endNumber = itemsPerPage * (selectedPage + 1);
    const endNumberToTotalItems = total < endNumber ? total : endNumber;
    const end = total === 0 ? 0 : endNumberToTotalItems;
    const endLimited = selectedPage * itemsPerPage + itemsPerPage;
    return isExceededTotalLimit ? t('{{start}}-{{endLimited}} of {{totalLimit}}+ items', {
      start,
      endLimited,
      totalLimit: totalLimit
    }) : t('{{start}}-{{end}} of {{total}} items', {
      start,
      end,
      total
    });
  };
  if (isLoading) {
    return /*#__PURE__*/_jsxs("div", {
      className: "pagination-container",
      children: [/*#__PURE__*/_jsx("div", {
        className: "pagination-buttons-container",
        children: /*#__PURE__*/_jsx(Skeleton, {
          type: SKELETON_TYPES.ROUNDED,
          width: 300,
          className: "pagination-loading-skeleton",
          testId: "pagination-loading-skeleton"
        })
      }), /*#__PURE__*/_jsx(Skeleton, {
        type: SKELETON_TYPES.ROUNDED,
        width: 90,
        className: "pagination-loading-skeleton",
        testId: "pagination-loading-skeleton"
      }), /*#__PURE__*/_jsx("div", {
        className: "pagination-summary-container",
        children: /*#__PURE__*/_jsx(Skeleton, {
          type: SKELETON_TYPES.ROUNDED,
          width: 120,
          className: "pagination-loading-skeleton",
          testId: "pagination-loading-skeleton"
        })
      })]
    });
  }
  return /*#__PURE__*/_jsxs("div", {
    className: "pagination-container",
    "aria-label": paginationGroupText ?? t('Pagination'),
    role: "group",
    children: [/*#__PURE__*/_jsxs("div", {
      className: "pagination-buttons-container",
      children: [/*#__PURE__*/_jsx(Button, {
        accentType: ACCENT_TYPES.GHOST,
        leftIcon: faChevronLeft,
        className: "pagination-prev-btn",
        isDisabled: selectedPage === 0,
        onClick: () => onPageSelect(selectedPage - 1),
        testId: "pagination-previous-btn",
        "aria-label": previousBtnText,
        children: previousBtnText
      }), /*#__PURE__*/_jsx(PagesButtons, {
        selectedPage: selectedPage,
        pageCount: numberOfPages,
        onPageSelect: onPageSelect
      }), /*#__PURE__*/_jsx(Button, {
        accentType: ACCENT_TYPES.GHOST,
        rightIcon: faChevronRight,
        className: "pagination-next-btn",
        isDisabled: isNextDisabled,
        onClick: () => onPageSelect(selectedPage + 1),
        testId: "pagination-next-btn",
        "aria-label": nextBtnText,
        children: nextBtnText
      })]
    }), /*#__PURE__*/_jsx(DropdownMenu, {
      options: itemsPerPageOptions,
      selectedKey: itemsPerPage,
      onSelect: selectedOption => {
        if (selectedOption) {
          onItemsPerPageChange(selectedOption.key);
        }
      },
      triggerDynamicContent: () => /*#__PURE__*/_jsx(TruncateWithTooltip, {
        children: /*#__PURE__*/_jsxs(_Fragment, {
          children: [/*#__PURE__*/_jsx("span", {
            className: "long-page-size-trigger-name",
            children: getSelectedPageSizeText?.(itemsPerPage, total) ?? t('{{pages}} per page', {
              pages: total < itemsPerPage ? total : itemsPerPage
            })
          }), /*#__PURE__*/_jsx("span", {
            className: "short-page-size-trigger-name",
            children: itemsPerPage
          })]
        })
      }),
      isDisabled: total === 0,
      triggerClassName: "pagination-items-per-page-dropdown",
      triggerId: perPageTriggerId,
      triggerTestId: "pagination-items-per-page-trigger",
      contentTestId: "pagination-items-per-page-dropdown-content"
    }), /*#__PURE__*/_jsx("div", {
      className: "pagination-summary-container",
      "test-id": "pagination-summary-container",
      children: /*#__PURE__*/_jsx(TruncateWithTooltip, {
        children: /*#__PURE__*/_jsx("span", {
          children: getPaginationSummaryText?.({
            selectedPage,
            itemsPerPage,
            total,
            totalLimit,
            isExceededTotalLimit
          }) ?? getDefaultPaginationSummaryText()
        })
      })
    })]
  });
}
export default /*#__PURE__*/memo(PaginationNew);