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

/**
 * TextInput — composite field: label + input + hint/error.
 *
 * Замена @nstart/ui TextInput (тот же API): label, hint, error, required.
 * Внутри использует наш shadcn Input primitive.
 */

export type TextInputProps = Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'> & {
  label?: React.ReactNode
  hint?: React.ReactNode
  error?: React.ReactNode
  required?: boolean
  /** Wrapper className (label + input + hint stack). */
  rootClassName?: string
}

export const TextInput = React.forwardRef<HTMLInputElement, TextInputProps>(
  function TextInput(
    { label, hint, error, required, rootClassName, className, id, ...props },
    ref,
  ) {
    const autoId = React.useId()
    const inputId = id ?? autoId
    const hintId = hint ? `${inputId}-hint` : undefined
    const errorId = error ? `${inputId}-error` : undefined
    return (
      <div className={cn('flex flex-col gap-1', rootClassName)}>
        {label && (
          <FieldLabel htmlFor={inputId} required={required}>
            {label}
          </FieldLabel>
        )}
        <Input
          ref={ref}
          id={inputId}
          aria-invalid={error ? true : undefined}
          aria-describedby={[hintId, errorId].filter(Boolean).join(' ') || undefined}
          className={cn(error ? 'border-pink focus-visible:ring-pink/40' : '', className)}
          required={required}
          {...props}
        />
        {hint && !error && <FieldHint id={hintId}>{hint}</FieldHint>}
        {error && <FieldError id={errorId}>{error}</FieldError>}
      </div>
    )
  },
)
