import * as React from 'react'

import { cn } from './utils'

interface FieldProps extends React.ComponentProps<'div'> {
  /** Label text displayed above the content */
  label?: string
  /** Associates the label with a form control via htmlFor */
  htmlFor?: string
  /** Whether the field is required (shows asterisk) */
  required?: boolean
  /** Hint text displayed below the content */
  hint?: string
  /** Error message displayed below the content (replaces hint when present) */
  error?: string
}

function Field({
  className,
  label,
  htmlFor,
  required,
  hint,
  error,
  children,
  ...props
}: FieldProps) {
  return (
    <div data-slot="field" className={cn('flex flex-col gap-1.5', className)} {...props}>
      {label && (
        <label
          data-slot="field-label"
          htmlFor={htmlFor}
          className="text-foreground text-sm font-medium leading-none"
        >
          {label}
          {required && (
            <span aria-hidden="true" className="text-accent-rose ml-0.5">
              *
            </span>
          )}
        </label>
      )}
      <div data-slot="field-content">{children}</div>
      {error ? (
        <p data-slot="field-error" role="alert" className="text-accent-rose text-xs">
          {error}
        </p>
      ) : hint ? (
        <p data-slot="field-hint" className="text-foreground-muted text-xs">
          {hint}
        </p>
      ) : null}
    </div>
  )
}

export { Field }
export type { FieldProps }
