import { clsx } from 'clsx';
import { useId } from 'react';
import InlineAlert from '../inlineAlert/InlineAlert.mjs';
import { FieldLabelIdContextProvider, InputIdContextProvider, InputDescribedByProvider, InputInvalidProvider } from '../inputs/contexts.mjs';
import { Label } from '../label/Label.mjs';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { Sentiment } from '../common/propsValues/sentiment.mjs';

const Field = ({
  id,
  label,
  required = true,
  message: propMessage,
  hint,
  description = hint,
  sentiment: propType = Sentiment.NEUTRAL,
  className,
  children,
  ...props
}) => {
  const sentiment = props.error ? Sentiment.NEGATIVE : propType;
  const message = propMessage || props.error;
  const hasError = sentiment === Sentiment.NEGATIVE;
  const labelId = useId();
  const fallbackInputId = useId();
  const inputId = id !== null ? id ?? fallbackInputId : undefined;
  const messageId = useId();
  const descriptionId = useId();
  /**
   * form control can have multiple messages to describe it,
   * e.g the description underneath the label and inline alert
   */
  function ariaDescribedbyByIds() {
    const messageIds = [];
    if (description) {
      messageIds.push(descriptionId);
    }
    if (message) {
      messageIds.push(messageId);
    }
    return messageIds.length > 0 ? messageIds.join(' ') : undefined;
  }
  return /*#__PURE__*/jsx(FieldLabelIdContextProvider, {
    value: labelId,
    children: /*#__PURE__*/jsx(InputIdContextProvider, {
      value: inputId,
      children: /*#__PURE__*/jsx(InputDescribedByProvider, {
        value: ariaDescribedbyByIds(),
        children: /*#__PURE__*/jsx(InputInvalidProvider, {
          value: hasError,
          children: /*#__PURE__*/jsxs("div", {
            className: clsx('np-field form-group d-block', {
              'has-success': sentiment === Sentiment.POSITIVE,
              'has-warning': sentiment === Sentiment.WARNING,
              'has-error': hasError,
              'has-info': sentiment === Sentiment.NEUTRAL
            }, className),
            children: [label != null ? /*#__PURE__*/jsxs(Fragment, {
              children: [/*#__PURE__*/jsx(Label, {
                id: labelId,
                htmlFor: inputId,
                children: required ? label : /*#__PURE__*/jsx(Label.Optional, {
                  children: label
                })
              }), /*#__PURE__*/jsx(Label.Description, {
                id: descriptionId,
                children: description
              }), /*#__PURE__*/jsx("div", {
                className: "np-field-control",
                children: children
              })]
            }) : children, message && /*#__PURE__*/jsx(InlineAlert, {
              type: sentiment,
              id: messageId,
              children: message
            })]
          })
        })
      })
    })
  });
};

export { Field };
//# sourceMappingURL=Field.mjs.map
