"use client";

/**
 * Range Slider Field
 *
 * A dual-thumb slider for selecting a min/max range.
 */

import { useCallback, useMemo } from "react";
import {
	ANIMATION_CLASSES,
	getStaggerStyle,
	STAGGER_PRESETS,
} from "../animations";
import { OnboardingLabel } from "../primitives/onboarding-label";
import { OnboardingSlider } from "../primitives/onboarding-slider";
import type { RangeSliderFieldProps } from "../types/fields";

export function RangeSliderField({
	id,
	label,
	description,
	min,
	max,
	step = 1,
	value,
	onChange,
	unit = "",
	unitPosition = "prefix",
	formatValue,
	showMinMax = true,
	animationIndex = 0,
	disabled = false,
}: RangeSliderFieldProps) {
	const handleChange = useCallback(
		(newValue: number[]) => {
			onChange([newValue[0], newValue[1]]);
		},
		[onChange],
	);

	const formatDisplayValue = useCallback(
		(val: number) => {
			if (formatValue) return formatValue(val);
			const formatted = val.toLocaleString();
			if (!unit) return formatted;
			return unitPosition === "prefix"
				? `${unit}${formatted}`
				: `${formatted} ${unit}`;
		},
		[formatValue, unit, unitPosition],
	);

	const displayRange = useMemo(() => {
		return `${formatDisplayValue(value[0])} – ${formatDisplayValue(value[1])}`;
	}, [value, formatDisplayValue]);

	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}
			</OnboardingLabel>

			{description && (
				<p className="mb-4 text-sm text-muted-foreground">
					{description.includes("{range}")
						? description.replace("{range}", displayRange)
						: description}
				</p>
			)}

			{!description && (
				<p className="mb-3 text-sm text-muted-foreground">
					<span className="font-medium tabular-nums">
						{formatDisplayValue(value[0])}
					</span>
					{" – "}
					<span className="font-medium tabular-nums">
						{formatDisplayValue(value[1])}
					</span>
				</p>
			)}

			<OnboardingSlider
				id={id}
				value={value}
				onValueChange={handleChange}
				min={min}
				max={max}
				step={step}
				disabled={disabled}
				aria-label={label}
			/>

			{showMinMax && (
				<div className="mt-2 flex justify-between text-xs text-muted-foreground">
					<span>{formatDisplayValue(min)}</span>
					<span>{formatDisplayValue(max)}</span>
				</div>
			)}
		</div>
	);
}
