import { Selector } from '@astryxdesign/core/Selector'
import { useId, type JSX } from 'react'
import { FieldShell, type FieldLabelMode } from './internal/field'

export interface SelectOption {
  value: string
  label: string
  disabled?: boolean
}

export interface SelectProps {
  label: string
  value: string
  options: readonly SelectOption[]
  onValueChange(value: string): void
  labelMode?: FieldLabelMode
  hint?: string
  error?: string
  placeholder?: string
  id?: string
  name?: string
  disabled?: boolean
  isDisabled?: boolean
  'data-testid'?: string
}

export function Select({
  label,
  value,
  options,
  onValueChange,
  labelMode = 'above',
  hint,
  error,
  placeholder,
  isDisabled,
  disabled,
  name,
  id: _id,
  ...rest
}: SelectProps): JSX.Element {
  const shellId = useId()
  const disabledState = isDisabled ?? disabled
  const needsShell = labelMode === 'inline'
  const control = (
    <Selector
      {...rest}
      label={label}
      isLabelHidden={needsShell ? true : labelMode === 'hidden'}
      options={[...options]}
      value={value}
      onChange={(next) => onValueChange(next)}
      htmlName={name}
      placeholder={placeholder}
      isDisabled={disabledState}
      description={hint}
      status={error !== undefined ? { type: 'error', message: error } : undefined}
    />
  )

  if (!needsShell) return control

  return (
    <FieldShell controlId={shellId} label={label} labelMode={labelMode}>
      {control}
    </FieldShell>
  )
}