import React, { useEffect, useRef } from 'react'; import { DailyStat, MedicationStat } from '../../types'; import BarChart from '../ui/BarChart'; import { BarChartIcon, getMedicationIcon } from '../icons/Icons'; interface StatsModalProps { isOpen: boolean; onClose: () => void; dailyStats: DailyStat[]; medicationStats: MedicationStat[]; } const formatLastTaken = (isoString?: string) => { if (!isoString) return N/A; const date = new Date(isoString); const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const yesterday = new Date( now.getFullYear(), now.getMonth(), now.getDate() - 1 ); const timeString = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', }); const datePart = new Date( date.getFullYear(), date.getMonth(), date.getDate() ); if (datePart.getTime() === today.getTime()) { return `Today at ${timeString}`; } if (datePart.getTime() === yesterday.getTime()) { return `Yesterday at ${timeString}`; } return date.toLocaleDateString(); }; const StatsModal: React.FC = ({ isOpen, onClose, dailyStats, medicationStats, }) => { const modalRef = useRef(null); const closeButtonRef = useRef(null); useEffect(() => { if (isOpen) { setTimeout(() => closeButtonRef.current?.focus(), 100); } }, [isOpen]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); }; if (isOpen) { window.addEventListener('keydown', handleKeyDown); } return () => window.removeEventListener('keydown', handleKeyDown); }, [isOpen, onClose]); if (!isOpen) return null; const hasData = medicationStats.length > 0; return (

Medication Statistics

{hasData ? ( <>

Weekly Adherence

Medication Breakdown

{medicationStats.map( ({ medication, taken, missed, upcoming, adherence, lastTakenAt, }) => { const MedicationIcon = getMedicationIcon( medication.icon ); const adherenceColor = adherence >= 90 ? 'text-green-600 dark:text-green-400' : adherence >= 70 ? 'text-amber-600 dark:text-amber-400' : 'text-red-600 dark:text-red-400'; return ( ); } )}
Medication Taken Missed Upcoming Last Taken Adherence
{medication.name}
{medication.dosage}
{taken} {missed} {upcoming} {formatLastTaken(lastTakenAt)} {adherence}%
) : (

Not enough data to display stats.

Statistics will appear here once you start tracking your doses.

)}
); }; export default StatsModal;