"use client";

/**
 * Date Picker Field (NEW)
 *
 * Combines Shadcn Popover and Calendar for date selection
 */

import { Calendar } from "@mdxui/primitives/calendar";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "@mdxui/primitives/popover";
import { format, isAfter, isBefore, isSameDay } from "date-fns";
import { CalendarIcon } from "lucide-react";
import { useMemo, useState } from "react";
import {
	ANIMATION_CLASSES,
	getStaggerStyle,
	STAGGER_PRESETS,
} from "../animations";
import { cx } from "../lib/utils";
import { OnboardingButton } from "../primitives/onboarding-button";
import { OnboardingLabel } from "../primitives/onboarding-label";
import type { DatePickerFieldProps } from "../types/fields";

export function DatePickerField({
	id,
	label,
	placeholder = "Pick a date",
	description,
	required = false,
	value,
	onChange,
	minDate,
	maxDate,
	disabledDates,
	animationIndex = 0,
	disabled = false,
	error,
	touched = false,
}: DatePickerFieldProps) {
	const [open, setOpen] = useState(false);

	const handleSelect = (date: Date | undefined) => {
		onChange(date);
		setOpen(false);
	};

	// Build disabled function for react-day-picker
	const isDateDisabled = useMemo(() => {
		return (date: Date) => {
			if (minDate && isBefore(date, minDate)) return true;
			if (maxDate && isAfter(date, maxDate)) return true;
			if (disabledDates?.some((d) => isSameDay(date, d))) return true;
			return false;
		};
	}, [minDate, maxDate, disabledDates]);

	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>
			)}

			<Popover open={open} onOpenChange={setOpen}>
				<PopoverTrigger asChild>
					<OnboardingButton
						id={id}
						variant="secondary"
						className={cx(
							"w-full justify-start text-left font-normal",
							!value && "text-muted-foreground",
							touched && error && "border-destructive",
						)}
						disabled={disabled}
					>
						<CalendarIcon className="mr-2 h-4 w-4" />
						{value ? format(value, "PPP") : placeholder}
					</OnboardingButton>
				</PopoverTrigger>
				<PopoverContent className="w-auto p-0" align="start">
					<Calendar
						mode="single"
						selected={value}
						onSelect={handleSelect}
						disabled={isDateDisabled}
						initialFocus
					/>
				</PopoverContent>
			</Popover>

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