"use client";

/**
 * Scale Input Field
 *
 * COPIED VERBATIM FROM: components/onboarding/steps/scale-input-step.tsx:81-141
 * Renders a slider or numeric input with optional value display
 */

import {
	ANIMATION_CLASSES,
	getStaggerStyle,
	STAGGER_PRESETS,
} from "../animations";
import { OnboardingInput } from "../primitives/onboarding-input";
import { OnboardingLabel } from "../primitives/onboarding-label";
import { OnboardingSlider } from "../primitives/onboarding-slider";
import type { ScaleInputFieldProps } from "../types/fields";

/**
 * Default value formatter
 * COPIED VERBATIM FROM: components/onboarding/steps/scale-input-step.tsx:61-72
 */
function defaultFormatValue(value: number): string {
	if (value >= 1_000_000_000) {
		return `${(value / 1_000_000_000).toFixed(1)}B`;
	}
	if (value >= 1_000_000) {
		return `${(value / 1_000_000).toFixed(1)}M`;
	}
	if (value >= 1_000) {
		return `${(value / 1_000).toFixed(1)}K`;
	}
	return value.toString();
}

export function ScaleInputField({
	id,
	label,
	description,
	min,
	max,
	step = 1,
	value,
	onChange,
	unit,
	formatValue,
	showSlider = true,
	animationIndex = 0,
	disabled = false,
}: ScaleInputFieldProps) {
	const displayValue = formatValue
		? formatValue(value)
		: defaultFormatValue(value);

	return (
		<div
			className={`space-y-3 ${ANIMATION_CLASSES.fadeInUp}`}
			style={getStaggerStyle(
				animationIndex,
				STAGGER_PRESETS.scaleFields.baseDelay,
				STAGGER_PRESETS.scaleFields.increment,
				STAGGER_PRESETS.scaleFields.duration,
			)}
		>
			<div className="flex items-baseline justify-between gap-4">
				<OnboardingLabel
					className="text-base font-medium text-foreground"
					htmlFor={id}
				>
					{label}
				</OnboardingLabel>
				{unit && <span className="text-sm text-muted-foreground">{unit}</span>}
			</div>

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

			<div className="flex items-center gap-4">
				{showSlider ? (
					<>
						<OnboardingSlider
							id={id}
							value={[value]}
							onValueChange={([newValue]) => onChange(newValue)}
							min={min}
							max={max}
							step={step}
							aria-valuetext={`${displayValue} ${unit || ""}`}
							className="flex-1"
							disabled={disabled}
						/>
						<div className="flex h-8 min-w-16 items-center justify-center rounded border border-border bg-background px-2 text-sm font-medium text-foreground">
							<span>{displayValue}</span>
						</div>
					</>
				) : (
					<OnboardingInput
						id={id}
						type="number"
						min={min}
						max={max}
						step={step}
						value={value}
						onChange={(e) => onChange(Number(e.target.value))}
						className="max-w-32"
						disabled={disabled}
					/>
				)}
			</div>
		</div>
	);
}
