import React, { useState, useEffect, useCallback } from 'react'; import { useAuth } from '../context/AuthContext'; import { useToast } from '../components/Toast'; import FillModal from '../components/FillModal'; import TemplateCard from '../components/TemplateCard'; import { apiFetch } from '../utils/api'; export default function Dashboard({ onNavigate }) { const { user } = useAuth(); const toast = useToast(); const isAdmin = user?.role === 'admin'; const [templates, setTemplates] = useState([]); const [stats, setStats] = useState(null); const [search, setSearch] = useState(''); const [loading, setLoading] = useState(true); const [fillTemplate, setFillTemplate] = useState(null); // Pagination für die Vorlagen-Table-Liste (10 Einträge pro Seite) const TEMPLATES_PER_PAGE = 10; const [currentPage, setCurrentPage] = useState(1); const fetchTemplates = useCallback(async () => { try { const res = await apiFetch('/templates'); const data = await res.json(); setTemplates(data); } catch (e) { console.error('Fehler beim Laden der Vorlagen:', e); } finally { setLoading(false); } }, []); const fetchStats = useCallback(async () => { if (!isAdmin) return; try { const res = await apiFetch('/stats'); if (res.ok) { const data = await res.json(); setStats(data); } } catch (e) { console.error('Fehler beim Laden der Statistiken:', e); } }, [isAdmin]); useEffect(() => { fetchTemplates(); fetchStats(); const interval = setInterval(fetchTemplates, 30000); return () => clearInterval(interval); }, [fetchTemplates, fetchStats]); // Alle Vorlagen sind für jeden User sichtbar (nicht mehr nach is_assignable gefiltert) const topTemplates = stats?.topTemplates || []; const filtered = templates.filter((t) => t.name.toLowerCase().includes(search.toLowerCase()) || (t.description || '').toLowerCase().includes(search.toLowerCase()) ); // Pagination: Suchwechsel setzt auf Seite 1 zurück const totalPages = Math.max(Math.ceil(filtered.length / TEMPLATES_PER_PAGE), 1); const pagedTemplates = filtered.slice((currentPage - 1) * TEMPLATES_PER_PAGE, currentPage * TEMPLATES_PER_PAGE); useEffect(() => { setCurrentPage(1); }, [search]); const handleSubmitTask = async (payload) => { const res = await apiFetch('/tasks', { method: 'POST', body: JSON.stringify({ ...payload, user_id: user.id }), }); if (!res.ok) { const data = await res.json(); throw new Error(data.error || 'Fehler beim Absenden'); } setFillTemplate(null); toast.success('Aufgabe erfolgreich abgesendet!'); fetchStats(); }; if (loading) { return (
Keine Vorlagen vorhanden.
Keine Vorlagen für „{search}" gefunden.