import * as React from "react";
import { Label } from "./label";
import { cn } from "@/lib/utils";

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

/** Wrapper pairing a label, an input, and its validation error/hint text. */
export function FormField({ label, htmlFor, group, error, hint, required, className, children }: FormFieldProps) {
  const labelId = React.useId();
  const generatedId = React.useId();
  const id = htmlFor || generatedId;

  const child = React.Children.only(children) as React.ReactElement<{ id?: string }>;
  const childWithId = React.isValidElement<{ id?: string }>(child) && !child.props.id
    ? React.cloneElement(child, { id })
    : child;

  if (group) {
    return (
      <div className={cn("space-y-2", className)}>
        <span id={labelId} className="text-sm font-medium text-(--color-ink)">
          {label}
          {required && <span className="text-(--color-danger) ml-0.5">*</span>}
        </span>
        <div role="radiogroup" aria-labelledby={labelId}>
          {childWithId}
        </div>
        {error ? (
          <p className="text-xs text-(--color-danger) font-medium mt-1">{error}</p>
        ) : hint ? (
          <p className="text-xs text-(--color-ink-muted) leading-relaxed mt-1">{hint}</p>
        ) : null}
      </div>
    );
  }

  return (
    <div className={cn("space-y-2", className)}>
      {htmlFor ? (
        <Label htmlFor={htmlFor} className="text-sm font-medium text-(--color-ink)">
          {label}
          {required && <span className="text-(--color-danger) ml-0.5">*</span>}
        </Label>
      ) : (
        <span id={labelId} className="text-sm font-medium text-(--color-ink)">
          {label}
          {required && <span className="text-(--color-danger) ml-0.5">*</span>}
        </span>
      )}
      {childWithId}
      {error ? (
        <p className="text-xs text-(--color-danger) font-medium mt-1">{error}</p>
      ) : hint ? (
        <p className="text-xs text-(--color-ink-muted) leading-relaxed mt-1">{hint}</p>
      ) : null}
    </div>
  );
}
