import { useState, useMemo } from "react"; import { AnimatePresence, motion } from "framer-motion"; import { ChevronLeft, ChevronRight } from "lucide-react"; import { startOfMonth, endOfMonth, startOfWeek, endOfWeek, eachDayOfInterval, format, isSameDay, isSameMonth, isToday as isTodayFn, isPast, addMonths, subMonths, setMonth, setYear, getYear, getMonth, } from "date-fns"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Button } from "@/components/ui/button"; interface CalendarPopoverProps { selectedDate: Date | null; onSelect: (date: Date) => void; onClear: () => void; children: React.ReactNode; } type ViewMode = "days" | "months" | "years"; const MONTH_NAMES = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]; export function CalendarPopover({ selectedDate, onSelect, onClear, children, }: CalendarPopoverProps) { const [open, setOpen] = useState(false); const [viewDate, setViewDate] = useState(() => selectedDate ?? new Date()); const [viewMode, setViewMode] = useState("days"); // Reset view when opening function handleOpenChange(nextOpen: boolean) { if (nextOpen) { setViewDate(selectedDate ?? new Date()); setViewMode("days"); } setOpen(nextOpen); } function handleSelectDate(date: Date) { onSelect(date); setOpen(false); } function handleToday() { const today = new Date(); onSelect(today); setOpen(false); } function handleClear() { onClear(); setOpen(false); } // Build the 6x7 grid of days for the current viewDate month const calendarDays = useMemo(() => { const monthStart = startOfMonth(viewDate); const monthEnd = endOfMonth(viewDate); const gridStart = startOfWeek(monthStart, { weekStartsOn: 1 }); // Monday const gridEnd = endOfWeek(monthEnd, { weekStartsOn: 1 }); return eachDayOfInterval({ start: gridStart, end: gridEnd }); }, [viewDate]); // Year range for year selector: current year +/- 5 const yearRange = useMemo(() => { const center = getYear(viewDate); const years: number[] = []; for (let y = center - 5; y <= center + 5; y++) { years.push(y); } return years; }, [viewDate]); return ( {children} {/* Navigation header */}
{/* Body: days / months / years */}
{viewMode === "days" && ( {/* Weekday headers */}
{WEEKDAYS.map((wd) => (
{wd}
))}
{/* Day grid */}
{calendarDays.map((day) => { const inMonth = isSameMonth(day, viewDate); const today = isTodayFn(day); const selected = selectedDate != null && isSameDay(day, selectedDate); const past = isPast(day) && !today; if (!inMonth) { return
; } return ( ); })}
)} {viewMode === "months" && ( {MONTH_NAMES.map((name, i) => ( ))} )} {viewMode === "years" && ( {yearRange.map((year) => ( ))} )}
{/* Footer */}
); }