'use client'

import React from 'react'

export interface FormFieldProps {
  label?: string
  error?: string
  helperText?: string
  required?: boolean
  htmlFor?: string
  children: React.ReactNode
  className?: string
}

export const FormField = ({
  label,
  error,
  helperText,
  required,
  htmlFor,
  children,
  className = '',
}: FormFieldProps) => {
  const errorId = htmlFor ? `${htmlFor}-error` : undefined
  const helperId = htmlFor ? `${htmlFor}-helper` : undefined

  return (
    <div className={`mb-4 ${className}`.trim()}>
      {label && (
        <label
          htmlFor={htmlFor}
          className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1"
        >
          {label}
          {required && (
            <span className="text-error-500 ml-1" aria-label="required">
              *
            </span>
          )}
        </label>
      )}

      {children}

      {error && (
        <p className="mt-1 text-sm text-error-500" id={errorId} role="alert">
          {error}
        </p>
      )}

      {helperText && !error && (
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400" id={helperId}>
          {helperText}
        </p>
      )}
    </div>
  )
}
