import {
  SimpleSelect as InstUISimpleSelect,
  type SimpleSelectProps as InstUISimpleSelectProps,
} from '@instructure/ui-simple-select'
import React, {forwardRef} from 'react'
import {enhanceErrorMessages} from '../../util/enhanceErrorMessages'

export interface SimpleSelectSubcomponents {
  Option: typeof InstUISimpleSelect.Option
  Group: typeof InstUISimpleSelect.Group
}

export interface SimpleSelectProps extends InstUISimpleSelectProps {}

const SimpleSelectComponent = forwardRef<InstUISimpleSelect, SimpleSelectProps>(
  ({messages, ...props}, ref) => {
    const messagesWithEnhancedErrors = enhanceErrorMessages(messages)

    return <InstUISimpleSelect {...props} ref={ref} messages={messagesWithEnhancedErrors} />
  },
)

/**
 * This is a wrapper around the InstUI `SimpleSelect` component.
 *
 * Differences include:
 * - If the `label` prop is a string, it will be enhanced with an asterisk if `isRequired` is `true`
 * - If the `messages` prop contains an error message, it will include an icon
 */
export const SimpleSelect = Object.assign(SimpleSelectComponent, {
  Option: InstUISimpleSelect.Option,
  Group: InstUISimpleSelect.Group,
}) as typeof SimpleSelectComponent & SimpleSelectSubcomponents
SimpleSelect.displayName = 'SimpleSelect'
