import React, { Children } from 'react'
import NovaSelect from './NovaSelect'

/**
 * Legacy Select wrapper.
 *
 * Accepts the same options API as a plain select:
 *   - Pass children (<option>, <optgroup>) directly, OR
 *   - Pass `options` array of { value, label } and optional `placeholder`
 *
 * @prop {Array}   options     - [{ value, label }] – optional shorthand
 * @prop {string}  placeholder - adds a blank first option when using `options`
 * @prop {string}  label       - field label
 * @prop {string}  error       - validation error
 * @prop {string}  hint        - helper text
 * @prop {boolean} required    - asterisk on label
 * @prop {string}  size        - ignored, kept for backward compatibility
 */
function Select({ label, error, hint, required, options, placeholder, size = 'md', id, className = '', children, ...rest }) {
  void size

  const normalizedOptions = options || Children.toArray(children).flatMap((child) => {
    if (!React.isValidElement(child)) return []

    if (child.type === 'optgroup') {
      const groupLabel = child.props.label
      return Children.toArray(child.props.children)
        .filter((optionChild) => React.isValidElement(optionChild))
        .map((optionChild) => ({
          value: optionChild.props.value,
          label: optionChild.props.children,
          group: groupLabel,
          disabled: optionChild.props.disabled,
        }))
    }

    return [{
      value: child.props.value,
      label: child.props.children,
      disabled: child.props.disabled,
    }]
  })

  return (
    <NovaSelect
      id={id}
      label={label}
      error={error}
      hint={hint}
      required={required}
      options={normalizedOptions}
      placeholder={placeholder}
      className={className}
      {...rest}
    />
  )
}

export default Select
