import type { ReactNode } from 'react'
import { Label } from '../Label/Label'
import styles from './FormField.module.css'

interface FormFieldProps {
  label?: string
  htmlFor?: string
  required?: boolean
  error?: string
  hint?: string
  children: ReactNode
  className?: string
}

export function FormField({
  label,
  htmlFor,
  required,
  error,
  hint,
  children,
  className,
}: FormFieldProps) {
  const wrapperClass = [styles.wrapper, error ? styles.error : '', className ?? '']
    .filter(Boolean)
    .join(' ')

  return (
    <div className={wrapperClass}>
      {label && (
        <Label htmlFor={htmlFor} required={required}>
          {label}
        </Label>
      )}
      {children}
      {error ? (
        <span className={styles.error} role="alert">
          {error}
        </span>
      ) : hint ? (
        <span className={styles.hint}>{hint}</span>
      ) : null}
    </div>
  )
}

FormField.displayName = 'FormField'
