"use client";

/**
 * Radio Group Field
 *
 * A simple radio button group with label, description, and error states.
 */

import {
	ANIMATION_CLASSES,
	getStaggerStyle,
	STAGGER_PRESETS,
} from "../animations";
import { cx } from "../lib/utils";
import { OnboardingLabel } from "../primitives/onboarding-label";
import {
	OnboardingRadioGroup,
	OnboardingRadioGroupItem,
} from "../primitives/onboarding-radio-group";
import type { RadioGroupFieldProps } from "../types/fields";

export function RadioGroupField({
	id,
	label,
	description,
	required = false,
	options,
	value,
	onChange,
	orientation = "vertical",
	error,
	touched = false,
	animationIndex = 0,
	disabled = false,
}: RadioGroupFieldProps) {
	return (
		<div
			className={ANIMATION_CLASSES.fadeInUp}
			style={getStaggerStyle(
				animationIndex,
				STAGGER_PRESETS.formFields.baseDelay,
				STAGGER_PRESETS.formFields.increment,
				STAGGER_PRESETS.formFields.duration,
			)}
		>
			<fieldset disabled={disabled}>
				<legend className="mb-2 text-base font-medium text-foreground">
					{label}
					{required && <span className="ml-1 text-destructive">*</span>}
				</legend>

				{description && (
					<p className="mb-3 text-sm text-muted-foreground">{description}</p>
				)}

				<OnboardingRadioGroup
					value={value}
					onValueChange={onChange}
					disabled={disabled}
					className={cx(
						orientation === "horizontal" &&
							"flex flex-row flex-wrap gap-x-6 gap-y-3",
						orientation === "vertical" && "flex flex-col gap-3",
					)}
					aria-labelledby={`${id}-legend`}
				>
					{options.map((option) => (
						<div
							key={option.value}
							className={cx(
								"flex items-start gap-2",
								orientation === "horizontal" && "items-center",
							)}
						>
							<OnboardingRadioGroupItem
								id={`${id}-${option.value}`}
								value={option.value}
								disabled={option.disabled}
								className="mt-0.5"
							/>
							<div className="flex flex-col">
								<OnboardingLabel
									htmlFor={`${id}-${option.value}`}
									className={cx(
										"font-normal cursor-pointer",
										option.disabled &&
											"text-muted-foreground cursor-not-allowed",
									)}
								>
									{option.label}
								</OnboardingLabel>
								{option.description && (
									<span className="text-sm text-muted-foreground">
										{option.description}
									</span>
								)}
							</div>
						</div>
					))}
				</OnboardingRadioGroup>
			</fieldset>

			{touched && error && (
				<p className="mt-1.5 text-sm text-destructive">{error}</p>
			)}
		</div>
	);
}
