import React, { forwardRef } from 'react';
import classNames from 'classnames';
import { faChevronDown } from '@fortawesome/free-solid-svg-icons/faChevronDown';
import { FontAwesomeIcon } from '../font-awesome-icon';
import { Tooltip, TOOLTIP_DELAY_TYPES } from '../tooltip';
import { TruncateWithTooltip } from '../truncate-with-tooltip';
import { DROPDOWN_MENU_SELECTBOX_SIZES } from './types';
import { BUTTON_TYPES } from '../button';
import DropdownItemTitle from './dropdown-item-title';
import { FormFieldLabel, getFormFieldLabelId } from '../form-field';
import { useDropdownTrigger } from './use-dropdown-trigger';
import { useTranslation } from '../hooks/use-translation';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const DefaultTriggerContent = function ({
  options = [],
  selectedItem,
  defaultTriggerText,
  isLarge = false
}) {
  if (selectedItem && isLarge) {
    return /*#__PURE__*/_jsx(DropdownItemTitle, {
      option: selectedItem
    });
  }
  const triggerContent = getGenericTriggerContent(selectedItem, options);
  const key = selectedItem?.key;
  if (triggerContent) {
    return /*#__PURE__*/_jsx("span", {
      className: "selected-item-details",
      children: /*#__PURE__*/_jsx(TruncateWithTooltip, {
        children: /*#__PURE__*/_jsx("span", {
          children: triggerContent
        })
      }, key)
    });
  }
  return /*#__PURE__*/_jsx(TruncateWithTooltip, {
    className: "placeholder",
    children: /*#__PURE__*/_jsx("span", {
      children: defaultTriggerText
    })
  }, key);
};
function getGenericTriggerContent(selectedItem, options) {
  const selectedOptions = options.filter(option => option.isChecked).map(option => option.title);
  if (selectedItem) {
    return selectedItem.title;
  }
  if (selectedOptions.length) {
    return selectedOptions.join(', ');
  }
  return null;
}
const DropdownSelectboxTrigger = /*#__PURE__*/forwardRef(({
  hasErrored,
  hasSuccess,
  hasWarnings,
  isOpen,
  isDisabled,
  isOptional,
  optionalLabelText,
  onClick,
  options,
  selectedItem,
  triggerOptions,
  isSectioned = false,
  selectbox
}, ref) => {
  const {
    t
  } = useTranslation();
  const {
    defaultTriggerText,
    labelText,
    helperText,
    triggerId,
    triggerTestId,
    triggerTooltip,
    triggerAriaLabelText,
    triggerTooltipPlacement,
    triggerDynamicContent,
    triggerOnClickHandler = () => {},
    triggerClassName,
    triggerTooltipDocLink,
    required,
    dropdownContentId,
    triggerTabIndex = 0
  } = triggerOptions || {};
  const {
    onMouseEnter,
    onMouseLeave,
    onMouseClick,
    onKeyDown
  } = useDropdownTrigger({
    onClick,
    triggerOnClickHandler,
    isOpen
  });
  const buttonAriaLabelledBy = [labelText ? getFormFieldLabelId(triggerId) : '',
  // announce label if exists
  `selected-item-${triggerId}` // announce selected item content
  ].filter(Boolean).join(' ');
  return /*#__PURE__*/_jsxs("div", {
    className: "selectbox",
    children: [labelText ? /*#__PURE__*/_jsx(FormFieldLabel, {
      id: triggerId,
      label: labelText,
      isOptional: isOptional,
      optionalLabelText: optionalLabelText ?? t('Optional'),
      isDisabled: isDisabled,
      isRequired: required
    }) : null, helperText && /*#__PURE__*/_jsx("div", {
      className: classNames('helper-text', isDisabled && 'disabled'),
      children: helperText
    }), /*#__PURE__*/_jsx("button", {
      type: BUTTON_TYPES.BUTTON,
      ref: ref,
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onMouseClick,
      onKeyDown: onKeyDown,
      "aria-haspopup": "menu",
      "aria-expanded": isOpen,
      "aria-label": triggerAriaLabelText ?? undefined,
      "aria-labelledby": buttonAriaLabelledBy
      // used by a screen reader to announce menu content if menu has no focus (opened with mouse click)
      ,
      ...(isOpen && {
        'aria-owns': dropdownContentId,
        'aria-controls': dropdownContentId
      }),
      disabled: isDisabled,
      "test-id": triggerTestId,
      id: triggerId,
      className: classNames('dropdown-trigger dropdown-selectbox-trigger', triggerClassName, {
        active: isOpen,
        sm: selectbox?.size === DROPDOWN_MENU_SELECTBOX_SIZES.SM,
        lg: selectbox?.size === DROPDOWN_MENU_SELECTBOX_SIZES.LG,
        xl: selectbox?.size === DROPDOWN_MENU_SELECTBOX_SIZES.XL,
        error: hasErrored,
        success: hasSuccess,
        warnings: hasWarnings,
        sectioned: isSectioned
      }),
      tabIndex: triggerTabIndex,
      children: /*#__PURE__*/_jsx(Tooltip, {
        content: triggerTooltip,
        placement: triggerTooltipPlacement,
        delayType: TOOLTIP_DELAY_TYPES.SLOW,
        docsLink: triggerTooltipDocLink,
        children: /*#__PURE__*/_jsxs("span", {
          id: `selected-item-${triggerId}`,
          className: "selected-item",
          children: [typeof triggerDynamicContent === 'function' ? triggerDynamicContent({
            isOpen
          }) : /*#__PURE__*/_jsx(DefaultTriggerContent, {
            options: options,
            selectedItem: selectedItem,
            defaultTriggerText: defaultTriggerText,
            isLarge: selectbox?.size === DROPDOWN_MENU_SELECTBOX_SIZES.XL || selectbox?.size === DROPDOWN_MENU_SELECTBOX_SIZES.LG
          }), /*#__PURE__*/_jsx(FontAwesomeIcon, {
            icon: faChevronDown,
            className: classNames('trigger-chevron-down', {
              expanded: isOpen
            })
          })]
        })
      })
    })]
  });
});
DropdownSelectboxTrigger.displayName = 'DropdownSelectboxTrigger';
export default DropdownSelectboxTrigger;