import * as React from 'react'
import { cn } from './cva'

export interface FieldControlState {
  id: string
  invalid: boolean
  required?: boolean
  describedBy?: string
}

export const FieldContext = React.createContext<FieldControlState | null>(null)

export function useFieldControl(): FieldControlState | null {
  return React.useContext(FieldContext)
}

export interface FieldProps {
  label: string
  htmlFor?: string
  hint?: string
  error?: string
  required?: boolean
  children: React.ReactNode
}

export function Field({ label, htmlFor, hint, error, required, children }: FieldProps) {
  const generatedId = React.useId()
  const controlId = htmlFor ?? generatedId
  const hintId = hint ? `${controlId}-hint` : undefined
  const errorId = error ? `${controlId}-error` : undefined
  const describedBy = [hintId, errorId].filter(Boolean).join(' ') || undefined

  return (
    <FieldContext.Provider value={{ id: controlId, invalid: Boolean(error), required, describedBy }}>
      <div className="flex flex-col gap-1">
        <label htmlFor={controlId} className="text-sm font-medium text-fg">
          {label}
          {required ? <span aria-hidden="true"> *</span> : null}
        </label>
        {children}
        {hint ? (
          <span id={hintId} className="text-sm text-fg-muted">
            {hint}
          </span>
        ) : null}
        {error ? (
          <span id={errorId} role="alert" className="text-sm text-danger">
            {error}
          </span>
        ) : null}
      </div>
    </FieldContext.Provider>
  )
}
