import React, { useRef, useEffect, useCallback } from 'react';
import classNames from 'classnames';
import { faFilter } from '@fortawesome/free-solid-svg-icons/faFilter';
import { Button, ACCENT_TYPES } from '../../button';
import { ActionBarSearch } from '../../action-bar-search';
import { useDebounce } from '../../hooks/use-debounce';
import { useTranslation } from '../../hooks/use-translation';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
export function TableToolbarActions({
  isFilterActive,
  onFilterClick,
  children,
  onSearchChange,
  searchQuery,
  filters,
  itemsFoundCount,
  isExceededTotalLimit,
  localizationText: localizationTextParams,
  filterButtonProps = {},
  searchProps = {}
}) {
  const itemsFoundRef = useRef(null);
  const {
    t
  } = useTranslation();
  const localizationText = localizationTextParams ?? {
    filter: t('Filters'),
    itemsFoundText: (count, isExceeded) => isExceeded ? t('{{count}}+ item found', {
      count,
      plural: '{{count}}+ items found'
    }) : t('{{count}} item found', {
      count,
      plural: '{{count}} items found'
    }),
    searchText: t('Search'),
    searchPlaceholder: t('Search')
  };
  const shouldShowItemsFoundCount = !!((searchQuery || filters?.length) && itemsFoundCount);
  const updateItemsFound = useCallback(itemCount => {
    if (itemsFoundRef.current) {
      itemsFoundRef.current.innerHTML = `${localizationText.itemsFoundText(itemCount, isExceededTotalLimit)}`;
    }
  }, [localizationText.itemsFoundText, isExceededTotalLimit]);
  const debouncedFunc = useDebounce(updateItemsFound, 1200);
  useEffect(() => {
    if (shouldShowItemsFoundCount && itemsFoundCount > 0) {
      debouncedFunc(itemsFoundCount);
    }
  }, [itemsFoundCount, shouldShowItemsFoundCount]);
  return /*#__PURE__*/_jsxs("div", {
    className: "table-toolbar-actions",
    children: [children, onFilterClick && /*#__PURE__*/_jsx(Button, {
      accentType: ACCENT_TYPES.GHOST,
      onClick: onFilterClick,
      leftIcon: faFilter,
      ...filterButtonProps,
      className: classNames(isFilterActive && 'active', filterButtonProps.className),
      "aria-pressed": isFilterActive,
      children: localizationText.filter
    }), onSearchChange && /*#__PURE__*/_jsx(ActionBarSearch, {
      searchQuery: searchQuery,
      onChange: onSearchChange,
      searchText: localizationText.searchText,
      focusPlaceholder: localizationText.searchPlaceholder,
      ...searchProps
    }), shouldShowItemsFoundCount && /*#__PURE__*/_jsxs("div", {
      className: "table-toolbar-actions-items-found",
      "test-id": "table-toolbar-actions-items-found",
      children: [/*#__PURE__*/_jsx("span", {
        children: localizationText.itemsFoundText(itemsFoundCount, isExceededTotalLimit)
      }), /*#__PURE__*/_jsx("span", {
        className: "sr-only",
        "aria-live": "polite",
        "test-id": "table-toolbar-actions-items-found-hidden",
        ref: itemsFoundRef
      })]
    })]
  });
}