'use client' import * as React from 'react' import { format, setHours, setMinutes } from 'date-fns' import { CalendarIcon, Clock } from 'lucide-react' import { cn } from '@/lib/utils' import { Button } from '@/components/ui/button' import { Calendar } from '@/components/ui/calendar' import { Popover, PopoverContent, PopoverTrigger, } from '@/components/ui/popover' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' interface DateTimePickerProps { value?: Date | null onChange?: (date: Date | null) => void placeholder?: string disabled?: boolean className?: string /** If true, only shows date picker without time */ dateOnly?: boolean /** If true, allows clearing the value */ clearable?: boolean } // Generate hour options (00-23) const hours = Array.from({ length: 24 }, (_, i) => i) // Generate minute options (00, 15, 30, 45) for easier selection const minutes = [0, 15, 30, 45] export function DateTimePicker({ value, onChange, placeholder = 'Select date and time', disabled = false, className, dateOnly = false, clearable = true, }: DateTimePickerProps) { const [open, setOpen] = React.useState(false) const [selectedDate, setSelectedDate] = React.useState( value ?? undefined ) // Sync internal state with external value React.useEffect(() => { setSelectedDate(value ?? undefined) }, [value]) const handleDateSelect = (date: Date | undefined) => { if (!date) { setSelectedDate(undefined) onChange?.(null) return } // Preserve time from previous selection or use noon as default const newDate = selectedDate ? setHours(setMinutes(date, selectedDate.getMinutes()), selectedDate.getHours()) : setHours(setMinutes(date, 0), 12) // Default to noon setSelectedDate(newDate) onChange?.(newDate) } const handleTimeChange = (type: 'hour' | 'minute', valueStr: string) => { if (!selectedDate) return const numValue = parseInt(valueStr, 10) let newDate: Date if (type === 'hour') { newDate = setHours(selectedDate, numValue) } else { newDate = setMinutes(selectedDate, numValue) } setSelectedDate(newDate) onChange?.(newDate) } const handleClear = (e: React.MouseEvent) => { e.stopPropagation() setSelectedDate(undefined) onChange?.(null) } const formatDisplayDate = (date: Date) => { if (dateOnly) { return format(date, 'MMM d, yyyy') } return format(date, 'MMM d, yyyy HH:mm') } return (
{!dateOnly && (
Time: :
{selectedDate && (

Selected: {format(selectedDate, 'EEEE, MMMM d, yyyy')} at{' '} {format(selectedDate, 'HH:mm')}

)}
)}
) }