"use client"; import { useEffect, useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { RefreshCw, MessageSquare, Mail, MailOpen, Loader2 } from "lucide-react"; import Link from 'next/link'; interface Email { id: string; subject: string; from: string; fromName?: string; date: string; read: boolean; starred: boolean; folder: string; } interface EmailResponse { emails: Email[]; mailUrl: string; error?: string; } export function Email() { const [emails, setEmails] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [mailUrl, setMailUrl] = useState(null); useEffect(() => { fetchEmails(); }, []); const fetchEmails = async (isRefresh = false) => { setLoading(true); setError(null); try { const response = await fetch('/api/courrier?folder=INBOX&page=1&perPage=5' + (isRefresh ? '&refresh=true' : '')); if (!response.ok) { throw new Error('Failed to fetch emails'); } const data = await response.json(); if (data.error) { setError(data.error); setEmails([]); } else { // Transform data format if needed const transformedEmails = data.emails.map((email: any) => ({ id: email.id, subject: email.subject, from: email.from[0]?.address || '', fromName: email.from[0]?.name || '', date: email.date, read: email.flags.seen, starred: email.flags.flagged, folder: email.folder })) // Sort emails by date (most recent first) .sort((a: Email, b: Email) => new Date(b.date).getTime() - new Date(a.date).getTime()) .slice(0, 5); // Only show the first 5 emails setEmails(transformedEmails); setMailUrl('/courrier'); } } catch (error) { console.error('Error fetching emails:', error); setError('Failed to load emails'); setEmails([]); } finally { setLoading(false); } }; const formatDate = (dateString: string) => { try { const date = new Date(dateString); return new Intl.DateTimeFormat('fr-FR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(date); } catch (e) { return ''; } }; return ( Courrier {error ? (
{error}
) : loading && emails.length === 0 ? (

Chargement des emails...

) : emails.length === 0 ? (

Aucun email non lu

) : (
{emails.map((email) => (
{email.read ? : }

{email.fromName || email.from.split('@')[0]}

{formatDate(email.date)}

{email.subject}

))} {mailUrl && (
Voir tous les emails →
)}
)}
); }