"use client";

/**
 * Dropdown Field
 *
 * COPIED VERBATIM FROM: components/onboarding/steps/dropdown-select-step.tsx:122-182
 * Renders a select dropdown with optional grouped options
 */

import {
	ANIMATION_CLASSES,
	getStaggerStyle,
	STAGGER_PRESETS,
} from "../animations";
import { OnboardingLabel } from "../primitives/onboarding-label";
import {
	OnboardingSelect,
	OnboardingSelectContent,
	OnboardingSelectGroup,
	OnboardingSelectItem,
	OnboardingSelectTrigger,
	OnboardingSelectValue,
} from "../primitives/onboarding-select";
import type {
	DropdownFieldProps,
	DropdownOption,
	DropdownOptionGroup,
} from "../types/fields";

/**
 * Type guard for grouped options
 * COPIED VERBATIM FROM: components/onboarding/steps/dropdown-select-step.tsx:66-68
 */
function isGroupedOptions(
	options: DropdownOption[] | DropdownOptionGroup[],
): options is DropdownOptionGroup[] {
	return options.length > 0 && "options" in options[0];
}

export function DropdownField({
	id,
	label,
	placeholder = "Select...",
	description,
	required = false,
	options,
	value,
	onChange,
	animationIndex = 0,
	disabled = false,
}: DropdownFieldProps) {
	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>
			)}

			<OnboardingSelect
				value={value}
				onValueChange={onChange}
				disabled={disabled}
			>
				<OnboardingSelectTrigger id={id} className="w-full">
					<OnboardingSelectValue placeholder={placeholder} />
				</OnboardingSelectTrigger>
				<OnboardingSelectContent>
					{isGroupedOptions(options)
						? options.map((group) => (
								<OnboardingSelectGroup key={group.label}>
									<OnboardingLabel className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
										{group.label}
									</OnboardingLabel>
									{group.options.map((option) => (
										<OnboardingSelectItem
											key={option.value}
											value={option.value}
											disabled={option.disabled}
										>
											{option.label}
										</OnboardingSelectItem>
									))}
								</OnboardingSelectGroup>
							))
						: options.map((option) => (
								<OnboardingSelectItem
									key={option.value}
									value={option.value}
									disabled={option.disabled}
								>
									{option.label}
								</OnboardingSelectItem>
							))}
				</OnboardingSelectContent>
			</OnboardingSelect>
		</div>
	);
}
