import * as React from "react"
import { cn } from "../core/cn"

interface FormFieldProps {
  label?: string
  helperText?: string
  error?: string
  children: React.ReactNode
  className?: string
}

function FormField({ label, helperText, error, children, className }: FormFieldProps) {
  const id = React.useId()
  const inputId = `${id}-input`
  const helperId = `${id}-helper`
  const errorId = `${id}-error`

  const describedBy = [helperText ? helperId : null, error ? errorId : null].filter(Boolean).join(" ") || undefined

  const childWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child as React.ReactElement<Record<string, unknown>>, {
        id: inputId,
        "aria-invalid": error ? true : undefined,
        "aria-describedby": describedBy,
      })
    }
    return child
  })

  return (
    <div className={cn("flex flex-col gap-1.5", className)}>
      {label && <label htmlFor={inputId} className="text-sm font-medium text-foreground">{label}</label>}
      {childWithProps}
      {helperText && !error && <p id={helperId} className="text-sm text-muted-foreground">{helperText}</p>}
      {error && <p id={errorId} className="text-sm text-destructive">{error}</p>}
    </div>
  )
}

export { FormField }
export type { FormFieldProps }
