"use client";

/**
 * Text Input Field
 *
 * COPIED VERBATIM FROM: components/onboarding/steps/text-input-step.tsx:200-253
 * Renders a single text input or select field
 */

import {
	ANIMATION_CLASSES,
	getStaggerStyle,
	STAGGER_PRESETS,
} from "../animations";
import { cx } from "../lib/utils";
import { OnboardingInput } from "../primitives/onboarding-input";
import { OnboardingLabel } from "../primitives/onboarding-label";
import {
	OnboardingSelect,
	OnboardingSelectContent,
	OnboardingSelectItem,
	OnboardingSelectTrigger,
	OnboardingSelectValue,
} from "../primitives/onboarding-select";
import type { TextInputFieldProps } from "../types/fields";

export function TextInputField({
	id,
	label,
	placeholder,
	description,
	fieldType = "text",
	type = "text",
	options,
	required = false,
	value,
	onChange,
	onBlur,
	error,
	touched = false,
	animationIndex = 0,
	disabled = false,
}: TextInputFieldProps) {
	return (
		<div
			className={ANIMATION_CLASSES.fadeInUp}
			style={getStaggerStyle(
				animationIndex,
				STAGGER_PRESETS.formFields.baseDelay,
				STAGGER_PRESETS.formFields.increment,
				STAGGER_PRESETS.formFields.duration,
			)}
		>
			<OnboardingLabel
				className="mb-2 block text-base font-medium text-foreground"
				htmlFor={id}
			>
				{label}
				{required && <span className="ml-1 text-destructive">*</span>}
			</OnboardingLabel>

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

			{fieldType === "select" ? (
				<OnboardingSelect
					value={value}
					onValueChange={onChange}
					disabled={disabled}
				>
					<OnboardingSelectTrigger
						id={id}
						className={cx(touched && error && "border-destructive")}
					>
						<OnboardingSelectValue placeholder={placeholder} />
					</OnboardingSelectTrigger>
					<OnboardingSelectContent>
						{options?.map((option) => (
							<OnboardingSelectItem key={option.value} value={option.value}>
								{option.label}
							</OnboardingSelectItem>
						))}
					</OnboardingSelectContent>
				</OnboardingSelect>
			) : (
				<OnboardingInput
					id={id}
					type={type}
					placeholder={placeholder}
					value={value}
					onChange={(e) => onChange(e.target.value)}
					onBlur={onBlur}
					disabled={disabled}
					aria-invalid={touched && !!error}
					aria-describedby={error ? `${id}-error` : undefined}
					className={cx(touched && error && "border-destructive")}
				/>
			)}

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