import React, { useState, useEffect, useCallback } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { useCounters } from '../hooks/useCounters'; import { useAuth } from '../hooks/useAuth'; import { CounterWithStats, CounterEntry } from '../types'; import { countersAPI } from '../services/api'; import { ArrowLeft, Plus, Minus, Trash2, Calendar } from 'lucide-react'; import { format } from 'date-fns'; export const CounterDetail: React.FC = () => { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const { isAuthenticated } = useAuth(); const { incrementCounter, deleteCounter } = useCounters(); const [counter, setCounter] = useState(null); const [entries, setEntries] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isIncrementing, setIsIncrementing] = useState(false); const [error, setError] = useState(null); const loadCounterData = useCallback(async () => { if (!id) return; setIsLoading(true); setError(null); try { if (isAuthenticated) { // Load from API const [counterResponse, entriesResponse] = await Promise.all([ countersAPI.getCounter(parseInt(id)), countersAPI.getCounterEntries(parseInt(id)) ]); setCounter(counterResponse.data); setEntries(entriesResponse.data); } else { // Load from localStorage const counters = JSON.parse(localStorage.getItem('anonymous_counters') || '[]'); const foundCounter = counters.find((c: any) => c.id === id); if (foundCounter) { // Convert to CounterWithStats format const today = new Date().toISOString().split('T')[0]; const counterWithStats: CounterWithStats = { id: parseInt(foundCounter.id), name: foundCounter.name, description: foundCounter.description, created_at: foundCounter.created_at, updated_at: foundCounter.updated_at, total_value: foundCounter.total_value, today_value: foundCounter.entries[today] || 0, week_value: Object.entries(foundCounter.entries) .filter(([date]) => { const entryDate = new Date(date); const weekAgo = new Date(); weekAgo.setDate(weekAgo.getDate() - 7); return entryDate >= weekAgo; }) .reduce((sum, [, value]) => sum + (value as number), 0), month_value: Object.entries(foundCounter.entries) .filter(([date]) => { const entryDate = new Date(date); const monthAgo = new Date(); monthAgo.setMonth(monthAgo.getMonth() - 1); return entryDate >= monthAgo; }) .reduce((sum, [, value]) => sum + (value as number), 0), entry_count: Object.values(foundCounter.entries).reduce((sum: number, value: unknown) => sum + Math.abs(value as number), 0), }; setCounter(counterWithStats); // Convert entries to CounterEntry format const counterEntries: CounterEntry[] = Object.entries(foundCounter.entries) .map(([date, value]) => ({ id: Math.random(), // Generate random ID for display counter_id: parseInt(foundCounter.id), value: value as number, date: date, created_at: new Date().toISOString(), })) .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); setEntries(counterEntries); } else { setError('Counter not found'); } } } catch (err: any) { setError(err.response?.data?.error || 'Failed to load counter'); } finally { setIsLoading(false); } }, [id, isAuthenticated]); useEffect(() => { if (id) { loadCounterData(); } }, [id, loadCounterData]); const handleIncrement = async (value: number) => { if (!counter) return; setIsIncrementing(true); try { await incrementCounter(counter.id, value); // Reload data to get updated values await loadCounterData(); } catch (error) { console.error('Failed to increment counter:', error); } finally { setIsIncrementing(false); } }; const handleDelete = async () => { if (!counter) return; if (window.confirm('Are you sure you want to delete this counter?')) { try { await deleteCounter(counter.id); navigate('/'); } catch (error) { console.error('Failed to delete counter:', error); } } }; if (isLoading) { return (
); } if (error || !counter) { return (
{error || 'Counter not found'}
); } return (
{/* Header */}

{counter.name}

{counter.description && (

{counter.description}

)}
{/* Counter Value and Controls */}
{counter.total_value}
Total Count
{/* Stats Grid */}
{counter.today_value}
Today
{counter.week_value}
This Week
{counter.month_value}
This Month
{/* Recent Entries */}

Recent Entries

{(entries?.length || 0) === 0 ? (
No entries yet. Start by incrementing your counter!
) : (
{entries?.slice(0, 10).map((entry) => (
0 ? 'bg-green-500' : 'bg-red-500' }`} /> {format(new Date(entry.date), 'MMM dd, yyyy')}
0 ? 'text-green-600' : 'text-red-600' }`}> {entry.value > 0 ? '+' : ''}{entry.value}
))}
)}
); };