import { useState } from 'react' interface EventScheduleConstraintInput { now: Date startDate?: string startTime?: number endDate?: string } export interface EventScheduleConstraints { todayIso: string startMinimumTime: number endMinimumTime: number } function isSameLocalDate(first: string | undefined, second: string): boolean { if (!first) return false const firstDate = new Date(first) const secondDate = new Date(second) return ( Number.isFinite(firstDate.getTime()) && Number.isFinite(secondDate.getTime()) && firstDate.getFullYear() === secondDate.getFullYear() && firstDate.getMonth() === secondDate.getMonth() && firstDate.getDate() === secondDate.getDate() ) } export function getEventScheduleConstraints({ now, startDate, startTime, endDate, }: EventScheduleConstraintInput): EventScheduleConstraints { const today = new Date(now) today.setHours(0, 0, 0, 0) const todayIso = today.toISOString() const nextMinute = Math.min(1440, now.getHours() * 60 + now.getMinutes() + 1) const startMinimumTime = isSameLocalDate(startDate, todayIso) ? nextMinute : 0 const endMinimumTime = isSameLocalDate(endDate, startDate || todayIso) ? Math.max(0, (startTime ?? 0) + 1) : isSameLocalDate(endDate, todayIso) ? nextMinute : 0 return { todayIso, startMinimumTime, endMinimumTime } } export function useEventScheduleConstraints( startDate: string | undefined, startTime: number | undefined, endDate: string | undefined ): EventScheduleConstraints { const [constraintNow] = useState(() => new Date()) return getEventScheduleConstraints({ now: constraintNow, startDate, startTime, endDate, }) }