import * as React from 'react';
import { cn } from '../utils/cn';
import { Label } from './Label';
import { Input, type InputProps } from './Input';
import { ErrorMessage } from './ErrorMessage';

export interface FormFieldProps extends Omit<InputProps, 'id' | 'error'> {
  /** Field label text */
  label: string;
  /** Field name (used for id and error lookup) */
  name: string;
  /** Error message for this field */
  error?: string;
  /** Additional description text */
  description?: string;
  /** Whether the field is required */
  required?: boolean;
  /** Container className */
  containerClassName?: string;
}

/**
 * FormField is a compound component that combines Label, Input, and ErrorMessage.
 *
 * @example
 * <FormField
 *   label="Email"
 *   name="email"
 *   type="email"
 *   error={errors.email}
 *   required
 * />
 *
 * @example
 * <FormField
 *   label="Password"
 *   name="password"
 *   type="password"
 *   description="Must be at least 8 characters"
 *   error={errors.password}
 * />
 */
const FormField = React.forwardRef<HTMLInputElement, FormFieldProps>(
  (
    {
      label,
      name,
      error,
      description,
      required,
      containerClassName,
      className,
      ...inputProps
    },
    ref
  ) => {
    const id = `field-${name}`;
    const descriptionId = description ? `${id}-description` : undefined;
    const errorId = error ? `${id}-error` : undefined;

    return (
      <div className={cn('space-y-1.5', containerClassName)}>
        <Label htmlFor={id} className="flex items-center gap-1">
          {label}
          {required && <span className="text-[var(--error)]">*</span>}
        </Label>

        {description && (
          <p id={descriptionId} className="text-sm text-[var(--text-muted)]">
            {description}
          </p>
        )}

        <Input
          ref={ref}
          id={id}
          name={name}
          error={!!error}
          aria-describedby={descriptionId}
          aria-invalid={!!error}
          aria-errormessage={errorId}
          className={className}
          {...inputProps}
        />

        <ErrorMessage id={errorId} message={error} />
      </div>
    );
  }
);
FormField.displayName = 'FormField';

export { FormField };
