'use client'; import { useState, useEffect, useCallback } from 'react'; import { MonthlyStats } from '@/types/ausgaben'; import { Category } from '@/app/api/categories/route'; interface MonatsStatistikProps { typ: number; refreshKey?: number; } export default function MonatsStatistik({ typ, refreshKey }: MonatsStatistikProps) { const [stats, setStats] = useState(null); const [month, setMonth] = useState(''); const [year, setYear] = useState(''); const [isLoading, setIsLoading] = useState(false); const [categories, setCategories] = useState([]); // Initialize month/year useEffect(() => { const now = new Date(); setMonth(String(now.getMonth() + 1).padStart(2, '0')); setYear(String(now.getFullYear())); }, []); // Fetch categories once useEffect(() => { fetch('/api/categories') .then((r) => r.json()) .then((data) => { if (data.success) setCategories(data.data); }) .catch(() => {}); }, []); const fetchStats = useCallback(async (y: string, m: string) => { if (!y || !m) return; setIsLoading(true); try { const response = await fetch(`/api/ausgaben/stats?year=${y}&month=${m}&typ=${typ}`); const data = await response.json(); if (data.success) setStats(data.data); } catch (error) { console.error('Error fetching stats:', error); } finally { setIsLoading(false); } }, [typ]); useEffect(() => { if (month && year) fetchStats(year, month); }, [month, year, typ, refreshKey, fetchStats]); const formatAmount = (amount: number) => new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(amount); const getCatLabel = (code: string) => { const cat = categories.find((c) => c.value === code); return cat ? `${cat.label}` : code; }; return (
{/* Zeile 1: Monat/Jahr + Gesamtsumme */}
setYear(e.target.value)} className="border border-gray-400 rounded px-3 py-1 w-24" min="2013" max="2099" />
{isLoading ? ( Lade... ) : stats ? ( Summe: {formatAmount(stats.totalAusgaben)} ) : null}
{/* Zeile 2+: Kategorien */} {!isLoading && stats?.katStats && Object.keys(stats.katStats).length > 0 && (
{Object.entries(stats.katStats).map(([code, total]) => (
{getCatLabel(code)}: {formatAmount(total)}
))}
)}
); }