import React, { forwardRef, useRef } from 'react';
// eslint-disable-next-line you-dont-need-lodash-underscore/get
import get from 'lodash-es/get';
import classNames from 'classnames';
import { Tooltip } from '../tooltip';
import { RADIO_BUTTON_SIZE } from './types';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/** Allows the user to select one option from a set
 * [CAPITALIZATION] Use sentence case
 * @midnight-gray-supported
 * @alpine-light-supported
 */
export const RadioButton = /*#__PURE__*/forwardRef(({
  option,
  checked,
  size,
  onSelect,
  groupIdentifier = '',
  ariaLabel = '',
  radioButtonRole,
  onKeyDown
}, ref) => {
  const getId = prefix => {
    return [prefix, groupIdentifier, option.id].filter(Boolean).join('-');
  };
  const wrapperRef = useRef(null);
  const itemId = getId('radiogroup-item');
  const labelId = getId('radiogroup-label');
  const helperId = getId('radiogroup-helper');
  const uniqueLabelId = `radiobutton-label-${option.id}`;
  const uniqueDescriptionId = `radiobutton-description-${option.id}`;
  const ariaAttr = {
    'aria-checked': checked,
    ...(option?.helperText && {
      'aria-describedby': uniqueDescriptionId
    }),
    ...(ariaLabel && {
      'aria-label': ariaLabel
    }),
    ...(!ariaLabel && (option.children || option.label) && {
      'aria-labelledby': uniqueLabelId
    }),
    role: radioButtonRole
  };
  const handleFocus = () => {
    // transition to the focused element when it was hidden by scroll
    wrapperRef?.current?.scrollIntoView?.({
      behavior: 'smooth',
      block: 'nearest'
    });
  };
  return /*#__PURE__*/_jsxs("div", {
    className: "radiobutton-wrapper",
    ref: wrapperRef,
    children: [/*#__PURE__*/_jsx("input", {
      ref: ref,
      className: "radiobutton",
      id: itemId,
      "test-id": itemId,
      type: "radio",
      disabled: option.disabled,
      value: option.id,
      checked: checked,
      onChange: e => onSelect?.(e.target.value),
      onFocus: handleFocus,
      name: groupIdentifier,
      onKeyDown: onKeyDown,
      ...ariaAttr
    }), /*#__PURE__*/_jsx(Tooltip, {
      placement: get(option, 'tooltipParams.placement'),
      content: get(option, 'tooltipParams.content'),
      children: /*#__PURE__*/_jsx("label", {
        "test-id": labelId,
        htmlFor: itemId,
        className: classNames('radiobutton-label', {
          lg: size === RADIO_BUTTON_SIZE.LG,
          'with-helper-text': option?.helperText
        }),
        id: uniqueLabelId,
        children: option.children || option.label
      })
    }), option?.helperText && /*#__PURE__*/_jsx("div", {
      className: "radiobutton-helper-text",
      "test-id": helperId,
      id: uniqueDescriptionId,
      children: option?.helperText
    })]
  });
});
RadioButton.displayName = 'RadioButton';