import { addMonths, eachDayOfInterval, endOfMonth, format, getDate, getDay, getHours, getMinutes, getMonth, getYear, isValid, } from 'date-fns' import { ChevronLeft, ChevronRight, Clock } from 'lucide-react' import React, { useEffect, useRef, useState } from 'react' import type { FieldProps } from './field-types' const DateField: React.FC> = ({ value, config, onSave, readOnly }) => { const dateConfig = config?.date const [isEditing, setIsEditing] = useState(false) const containerRef = useRef(null) // Parse value or default to today // Replaced parseISO with new Date() to avoid import errors const parsedDate = value ? new Date(value) : new Date() const safeDate = isValid(parsedDate) ? parsedDate : new Date() // Calendar State const [viewDate, setViewDate] = useState(safeDate) useEffect(() => { if (isEditing && value) { const d = new Date(value) if (isValid(d)) setViewDate(d) } }, [isEditing, value]) // Click outside to close useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(event.target as Node)) { if (isEditing) { setIsEditing(false) } } } document.addEventListener('mousedown', handleClickOutside) return () => document.removeEventListener('mousedown', handleClickOutside) }, [isEditing]) const handleStartEdit = () => { if (!readOnly) { setIsEditing(true) } } const getDisplayValue = (isoString: string) => { if (!isoString) return '' const date = new Date(isoString) if (!isValid(date)) return 'Invalid Date' let formatStr = 'PPP' // Default Friendly if (dateConfig?.displayFormat === 'usa') formatStr = 'MM/dd/yyyy' else if (dateConfig?.displayFormat === 'euro') formatStr = 'dd/MM/yyyy' else if (dateConfig?.displayFormat === 'iso') formatStr = 'yyyy-MM-dd' if (dateConfig?.includeTime) { if (dateConfig?.timeFormat === 'twenty_four_hour') { formatStr += ' HH:mm' } else { formatStr += ' p' } } let display = format(date, formatStr) if (dateConfig?.displayTimezone) { display += ` (${Intl.DateTimeFormat().resolvedOptions().timeZone})` } return display } // Calendar Logic // Replaced startOfMonth with native Date manipulation const monthStart = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1) const monthEnd = endOfMonth(viewDate) const daysInMonth = eachDayOfInterval({ start: monthStart, end: monthEnd }) const startDayOfWeek = getDay(monthStart) // 0 = Sunday const handleDateClick = (day: Date) => { // Preserve time from current value if exists const newDate = new Date(day) if (dateConfig?.includeTime) { // Replaced setHours/setMinutes with native methods newDate.setHours(getHours(safeDate)) newDate.setMinutes(getMinutes(safeDate)) } const isoString = newDate.toISOString() onSave(isoString) if (!dateConfig?.includeTime) { setIsEditing(false) } } const handleTimeChange = (type: 'hour' | 'minute', val: number) => { const newDate = value ? new Date(value) : new Date() if (!isValid(newDate)) newDate.setTime(new Date().getTime()) if (type === 'hour') newDate.setHours(val) if (type === 'minute') newDate.setMinutes(val) const isoString = newDate.toISOString() onSave(isoString) } const hours = Array.from({ length: 24 }, (_, i) => i) const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 0, 5, 10... if (isEditing) { return (
{value ? ( getDisplayValue(value) ) : ( Select date... )}
{/* Date Picker */}
{/* Replaced subMonths with addMonths(-1) */} {format(viewDate, 'MMMM yyyy')}
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
{d}
))}
{Array.from({ length: startDayOfWeek }).map((_, i) => (
))} {daysInMonth.map((date) => { const valDate = value ? new Date(value) : null const isSelected = valDate && isValid(valDate) && getDate(valDate) === getDate(date) && getMonth(valDate) === getMonth(date) && getYear(valDate) === getYear(date) return ( ) })}
{/* Time Picker */} {dateConfig?.includeTime && (
Time
{hours.map((h) => (
handleTimeChange('hour', h)} className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getHours(safeDate) === h ? 'bg-primary/10 font-medium text-primary' : ''}`} > {h.toString().padStart(2, '0')}
))}
{minutes.map((m) => (
handleTimeChange('minute', m)} className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getMinutes(safeDate) === m ? 'bg-primary/10 font-medium text-primary' : ''}`} > {m.toString().padStart(2, '0')}
))}
)}
) } return (
{value ? getDisplayValue(value) : Empty}
) } export default DateField