import { useState, useRef, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { Calendar } from "lucide-react"; import type { DashboardPeriod } from "../../shared/types"; const PERIODS: DashboardPeriod[] = ["month", "3months", "6months", "year", "12months", "all"]; interface PeriodSelectorProps { value: DashboardPeriod; onChange: (period: DashboardPeriod) => void; customDateFrom?: string; customDateTo?: string; onCustomDateChange?: (dateFrom: string, dateTo: string) => void; } export default function PeriodSelector({ value, onChange, customDateFrom, customDateTo, onCustomDateChange, }: PeriodSelectorProps) { const { t } = useTranslation(); const [showCustom, setShowCustom] = useState(false); const [localFrom, setLocalFrom] = useState(customDateFrom ?? ""); const [localTo, setLocalTo] = useState(customDateTo ?? ""); const panelRef = useRef(null); useEffect(() => { if (customDateFrom) setLocalFrom(customDateFrom); if (customDateTo) setLocalTo(customDateTo); }, [customDateFrom, customDateTo]); // Close panel on outside click useEffect(() => { if (!showCustom) return; function handleClick(e: MouseEvent) { if (panelRef.current && !panelRef.current.contains(e.target as Node)) { setShowCustom(false); } } document.addEventListener("mousedown", handleClick); return () => document.removeEventListener("mousedown", handleClick); }, [showCustom]); const handleApply = () => { if (localFrom && localTo && localFrom <= localTo && onCustomDateChange) { onCustomDateChange(localFrom, localTo); setShowCustom(false); } }; const isValid = localFrom && localTo && localFrom <= localTo; return (
{PERIODS.map((p) => ( ))} {onCustomDateChange && (
{showCustom && (
{ setLocalFrom(e.target.value); // Close native date popup on WebKitGTK (#177) e.currentTarget.blur(); }} className="px-3 py-1.5 rounded-lg text-sm border border-[var(--border)] bg-[var(--background)] text-[var(--foreground)]" />
{ setLocalTo(e.target.value); // Close native date popup on WebKitGTK (#177) e.currentTarget.blur(); }} className="px-3 py-1.5 rounded-lg text-sm border border-[var(--border)] bg-[var(--background)] text-[var(--foreground)]" />
)}
)}
); }