'use client'; import { useState, useEffect, useRef } from 'react'; import { useRouter } from 'next/navigation'; import TrajetForm from './TrajetForm'; import AdherentForm from './AdherentForm'; import TrajetDetailModal from './TrajetDetailModal'; import { getParticipationRef } from '@/lib/participation-ref'; type PeriodType = 'day' | 'yesterday' | 'week' | 'month' | 'quarter' | 'year' | 'custom'; interface Stats { periodLabel?: string; participationsMois: { montant: number; nombreFactures: number; }; trajetsAujourdhui: { nombre: number; difference: number; }; trajetsRealisesMois: { nombre: number; pourcentageEvolution: number; }; chauffeursActifs: { nombre: number; total: number; }; } interface Trajet { id: string; date: string; adresseDepart: string; adresseArrivee: string; commentaire?: string | null; statut: string; participations?: { id: string }[]; adherent: { id: string; nom: string; prenom: string; telephone: string; email: string; }; chauffeur?: { id: string; nom: string; prenom: string; telephone: string; } | null; } interface DashboardContentProps { userName?: string | null; } const PERIOD_OPTIONS: { value: PeriodType; label: string }[] = [ { value: 'day', label: "Aujourd'hui" }, { value: 'yesterday', label: 'Hier' }, { value: 'week', label: 'Cette semaine' }, { value: 'month', label: 'Ce mois-ci' }, { value: 'quarter', label: 'Ce trimestre' }, { value: 'year', label: 'Cette année' }, { value: 'custom', label: 'Personnalisé' }, ]; export default function DashboardContent({ userName }: DashboardContentProps) { const router = useRouter(); const [stats, setStats] = useState(null); const [trajetsRecents, setTrajetsRecents] = useState([]); const [loading, setLoading] = useState(true); const [period, setPeriod] = useState('month'); const [dropdownOpen, setDropdownOpen] = useState(false); const dropdownRef = useRef(null); const [customFrom, setCustomFrom] = useState(''); const [customTo, setCustomTo] = useState(''); const [showTrajetForm, setShowTrajetForm] = useState(false); const [showAdherentForm, setShowAdherentForm] = useState(false); const [selectedTrajet, setSelectedTrajet] = useState(null); useEffect(() => { if (period === 'custom' && customFrom && customTo) { fetchStatsCustom(customFrom, customTo); } else if (period !== 'custom') { fetchStats(period); } fetchTrajetsRecents(); }, [period, customFrom, customTo]); useEffect(() => { const handleClickOutside = (e: MouseEvent) => { if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) { setDropdownOpen(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); const fetchStats = async (p: PeriodType = period) => { if (p === 'custom') return; try { const params = new URLSearchParams({ period: p }); const response = await fetch(`/api/dashboard/stats?${params}`); if (response.ok) { const data = await response.json(); setStats(data); } } catch (error) { console.error('Erreur lors du chargement des statistiques:', error); } }; const fetchStatsCustom = async (from: string, to: string) => { try { const params = new URLSearchParams({ from, to }); const response = await fetch(`/api/dashboard/stats?${params}`); if (response.ok) { const data = await response.json(); setStats(data); } } catch (error) { console.error('Erreur lors du chargement des statistiques:', error); } }; const refreshStats = () => { if (period === 'custom' && customFrom && customTo) { fetchStatsCustom(customFrom, customTo); } else if (period !== 'custom') { fetchStats(period); } }; const fetchTrajetsRecents = async () => { setLoading(true); try { const response = await fetch('/api/trajets?limit=3'); if (response.ok) { const data = await response.json(); setTrajetsRecents(data); } } catch (error) { console.error('Erreur lors du chargement des trajets récents:', error); } finally { setLoading(false); } }; const formatDate = (dateString: string) => { const date = new Date(dateString); return date.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric', }); }; const formatTime = (dateString: string) => { const date = new Date(dateString); return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }); }; const getInitials = (nom: string, prenom: string) => { return `${prenom.charAt(0)}${nom.charAt(0)}`.toUpperCase(); }; // Montant estimé par trajet (basé sur l'image) const getMontantTrajet = () => { return 6.80; // Montant moyen }; return (
{/* En-tête avec menu déroulant de période */}

Content de vous revoir {userName || 'Utilisateur'}

Bienvenue sur votre tableau de bord.

{dropdownOpen && (

Période des statistiques

{PERIOD_OPTIONS.filter((o) => o.value !== 'custom').map((opt) => ( ))}
{period === 'custom' && (

Sélectionner une plage

setCustomFrom(e.target.value)} className="flex-1 px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-dyellow/30 focus:border-dyellow transition-shadow" /> setCustomTo(e.target.value)} className="flex-1 px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-dyellow/30 focus:border-dyellow transition-shadow" />
)}
)}
{/* Statistiques */}
{/* Participations du mois */}

Participations {period === 'month' ? 'ce mois-ci' : 'sur la période'}

{stats ? `${stats.participationsMois.montant.toFixed(2).replace('.', ',')}€` : '0,00€'}

{stats ? `${stats.participationsMois.nombreFactures} participation${stats.participationsMois.nombreFactures > 1 ? 's' : ''}` : '0 participation'}

{/* Trajets Aujourd'hui */}

Trajets {period === 'day' ? "aujourd'hui" : period === 'yesterday' ? 'hier' : 'sur la période'}

{stats ? stats.trajetsAujourdhui.nombre : 0}

{stats && stats.trajetsAujourdhui.difference !== 0 ? `${stats.trajetsAujourdhui.difference > 0 ? '+' : ''}${stats.trajetsAujourdhui.difference} vs période précédente` : 'Aucun changement'}

{/* Trajets réalisés ce mois */}

Trajets réalisés {period === 'month' ? 'ce mois-ci' : 'sur la période'}

{stats ? stats.trajetsRealisesMois.nombre : 0}

{stats && stats.trajetsRealisesMois.pourcentageEvolution !== 0 ? `${stats.trajetsRealisesMois.pourcentageEvolution > 0 ? '+' : ''}${stats.trajetsRealisesMois.pourcentageEvolution}% vs période précédente` : 'Aucun changement'}

{/* Chauffeurs actifs */}

Chauffeurs actifs

{stats ? stats.chauffeursActifs.nombre : 0}

{stats ? `Sur ${stats.chauffeursActifs.total} total` : 'Sur 0 total'}

{/* Actions Rapides et Trajets Récents côte à côte */}
{/* Actions Rapides */}

Actions Rapides

Bientôt ?

{/* Trajets Récents */}

Trajets Récents

{loading ? (
Chargement...
) : trajetsRecents.length === 0 ? (
Aucun trajet créé récemment
) : (
{trajetsRecents.map((trajet) => ( setSelectedTrajet(trajet)} className="border-b border-gray-100 last:border-b-0 hover:bg-gray-50/80 transition-colors cursor-pointer" > ))}
Adhérent Statut Fichier
{getInitials(trajet.adherent.nom, trajet.adherent.prenom)}
{trajet.adherent.prenom} {trajet.adherent.nom}

{formatDate(trajet.date)} · {formatTime(trajet.date)}

{trajet.statut} {trajet.participations?.[0] ? ( {getParticipationRef(trajet.participations[0].id)} ) : ( )}
)}
{/* Modals */} {showTrajetForm && ( setShowTrajetForm(false)} onSuccess={() => { setShowTrajetForm(false); fetchTrajetsRecents(); refreshStats(); }} /> )} {showAdherentForm && ( { setShowAdherentForm(false); refreshStats(); }} /> )} {selectedTrajet && ( setSelectedTrajet(null)} onUpdate={() => { fetchTrajetsRecents(); refreshStats(); }} /> )}
); }