'use client'; import { useState } from 'react'; import { Calendar } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; import { isCustomRange, type DateRange } from '@/lib/analytics/range'; interface DateRangePickerProps { value: DateRange; onChange: (next: DateRange) => void; className?: string; } const PRESETS: Array<{ value: 'today' | '7d' | '30d' | '90d'; label: string }> = [ { value: 'today', label: 'Today' }, { value: '7d', label: '7d' }, { value: '30d', label: '30d' }, { value: '90d', label: '90d' }, ]; /** * Format a custom range as a compact button label, e.g. "Apr 14 – May 4". * Same year omits the year on both sides; different years includes both. */ function formatCustom(range: { from: string; to: string }): string { const from = new Date(`${range.from}T00:00:00.000Z`); const to = new Date(`${range.to}T00:00:00.000Z`); const sameYear = from.getUTCFullYear() === to.getUTCFullYear(); const fmt: Intl.DateTimeFormatOptions = sameYear ? { month: 'short', day: 'numeric', timeZone: 'UTC' } : { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' }; return `${from.toLocaleDateString(undefined, fmt)} – ${to.toLocaleDateString(undefined, fmt)}`; } /** * Today's date as a YYYY-MM-DD string in UTC. Used as the default for the * "to" picker so users can't accidentally pick a future date by leaving the * field empty. */ function todayIso(): string { return new Date().toISOString().slice(0, 10); } export function DateRangePicker({ value, onChange, className }: DateRangePickerProps) { const [open, setOpen] = useState(false); const isCustom = isCustomRange(value); // Local state for the popover form. Seeded from the current value if it's // already custom, otherwise defaults to a 14-day window ending today. const [draftFrom, setDraftFrom] = useState(() => { if (isCustom) return value.from; const d = new Date(); d.setUTCDate(d.getUTCDate() - 14); return d.toISOString().slice(0, 10); }); const [draftTo, setDraftTo] = useState(() => (isCustom ? value.to : todayIso())); const today = todayIso(); const draftValid = draftFrom !== '' && draftTo !== '' && draftFrom <= draftTo && draftFrom <= today && draftTo <= today; function applyCustom() { if (!draftValid) return; onChange({ kind: 'custom', from: draftFrom, to: draftTo }); setOpen(false); } return (
{PRESETS.map((opt) => { const active = !isCustom && opt.value === value; return ( ); })} {/* Custom range - popover with two date inputs and an Apply button */}
Custom range
); }