"use client";

/**
 * Date Range Field
 *
 * Combines Shadcn Popover and Calendar for date range 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 type { DateRange } from "react-day-picker";
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 { DateRangeFieldProps } from "../types/fields";

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

	const handleSelect = (range: DateRange | undefined) => {
		onChange(range);
		// Keep popover open - user closes it by clicking outside or pressing Escape
	};

	// 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]);

	// Format the display text
	const displayText = useMemo(() => {
		if (!value?.from) return placeholder;
		if (!value.to) return format(value.from, "PPP");
		return `${format(value.from, "PP")} - ${format(value.to, "PP")}`;
	}, [value, placeholder]);

	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?.from && "text-muted-foreground",
							touched && error && "border-destructive",
						)}
						disabled={disabled}
					>
						<CalendarIcon className="mr-2 h-4 w-4" />
						{displayText}
					</OnboardingButton>
				</PopoverTrigger>
				<PopoverContent className="w-auto p-0" align="start">
					<Calendar
						mode="range"
						selected={value}
						onSelect={handleSelect}
						disabled={isDateDisabled}
						numberOfMonths={numberOfMonths}
						initialFocus
					/>
				</PopoverContent>
			</Popover>

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