import * as React from 'react'
import { FieldLabel, FieldHint, FieldError } from './field'
import { cn } from '@/lib/utils'

/**
 * SingleSelect — native &lt;select&gt; wrapped в label/hint/error chrome.
 * Замена @nstart/ui SingleSelect (тот же API: options, value, onChange).
 *
 * <p>Native select работает на mobile out-of-box, screen readers OK, по
 * Enter/space открывается. Custom dropdown UI можно сделать через Radix
 * Select (Stage 3.8b refinement) если потребуется branded look.
 */

/** nstart-compat shape: {id, label}. New code may prefer the more standard
 * {value, label} — both keys accepted (id wins if both). */
export type SelectOption = {
  id: string
  label: React.ReactNode
  /** Alias of `id` для совместимости с HTML option convention. */
  value?: string
}

export type SingleSelectProps = {
  label?: React.ReactNode
  hint?: React.ReactNode
  error?: React.ReactNode
  required?: boolean
  options: ReadonlyArray<SelectOption>
  value: string
  onChange: (value: string) => void
  placeholder?: string
  disabled?: boolean
  id?: string
  rootClassName?: string
  selectClassName?: string
}

export function SingleSelect({
  label,
  hint,
  error,
  required,
  options,
  value,
  onChange,
  placeholder,
  disabled,
  id,
  rootClassName,
  selectClassName,
}: SingleSelectProps) {
  const autoId = React.useId()
  const selectId = id ?? autoId
  const hintId = hint ? `${selectId}-hint` : undefined
  const errorId = error ? `${selectId}-error` : undefined
  return (
    <div className={cn('flex flex-col gap-1', rootClassName)}>
      {label && (
        <FieldLabel htmlFor={selectId} required={required}>
          {label}
        </FieldLabel>
      )}
      <select
        id={selectId}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        required={required}
        aria-invalid={error ? true : undefined}
        aria-describedby={[hintId, errorId].filter(Boolean).join(' ') || undefined}
        className={cn(
          'flex h-9 w-full rounded-md border border-line bg-surface px-3 text-body text-ink',
          'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
          'disabled:cursor-not-allowed disabled:opacity-50',
          error && 'border-pink focus-visible:ring-pink/40',
          selectClassName,
        )}
      >
        {placeholder !== undefined && <option value="">{placeholder}</option>}
        {options.map((opt) => {
          const v = opt.id ?? opt.value
          return (
            <option key={v} value={v}>
              {typeof opt.label === 'string' ? opt.label : v}
            </option>
          )
        })}
      </select>
      {hint && !error && <FieldHint id={hintId}>{hint}</FieldHint>}
      {error && <FieldError id={errorId}>{error}</FieldError>}
    </div>
  )
}
