import { format, parse } from "date-fns";
import { CalendarIcon } from "lucide-react";
import { type ComponentProps, useState } from "react";
import { Button } from "@/shared/components/ui/button";
import { Calendar } from "@/shared/components/ui/calendar";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "@/shared/components/ui/popover";
import { cn } from "@/shared/lib/utils";

interface DateInputProps
	extends Omit<ComponentProps<"button">, "value" | "onChange"> {
	value: string;
	onChange: (iso: string) => void;
	placeholder?: string;
}

function toDate(iso: string): Date | undefined {
	if (!iso) return undefined;
	const d = parse(iso, "yyyy-MM-dd", new Date());
	return Number.isNaN(d.getTime()) ? undefined : d;
}

function toISO(date: Date): string {
	return format(date, "yyyy-MM-dd");
}

export function DateInput({
	value,
	onChange,
	placeholder = "YYYY-MM-DD",
	className,
	id,
	...props
}: DateInputProps) {
	const [open, setOpen] = useState(false);
	const selected = toDate(value);

	return (
		<Popover open={open} onOpenChange={setOpen}>
			<PopoverTrigger asChild>
				<Button
					id={id}
					type="button"
					variant="outline"
					className={cn(
						"h-9 w-full justify-start px-3 text-left font-normal",
						!value && "text-muted-foreground",
						className,
					)}
					{...props}
				>
					<CalendarIcon className="mr-2 size-4 shrink-0" />
					{value || placeholder}
				</Button>
			</PopoverTrigger>
			<PopoverContent className="w-auto p-0" align="start">
				<Calendar
					mode="single"
					selected={selected}
					onSelect={(day) => {
						if (day) {
							onChange(toISO(day));
							setOpen(false);
						}
					}}
					defaultMonth={selected}
				/>
			</PopoverContent>
		</Popover>
	);
}
