"use client"; import { useEffect, useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { RefreshCw, Mail } from "lucide-react"; import { useSession, signIn } from "next-auth/react"; import { formatDistance } from 'date-fns/formatDistance'; import { fr } from 'date-fns/locale/fr'; import { useRouter } from "next/navigation"; 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 [mailUrl, setMailUrl] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [refreshing, setRefreshing] = useState(false); const { status } = useSession(); const router = useRouter(); const fetchEmails = async (isRefresh = false) => { if (isRefresh) setRefreshing(true); if (!isRefresh) setLoading(true); try { console.log('Starting fetch request...'); const response = await fetch('/api/mail'); console.log('Response status:', response.status); if (!response.ok) { if (response.status === 401) { signIn(); return; } const errorData = await response.json(); throw new Error(errorData.error || 'Failed to fetch emails'); } const data = await response.json(); console.log('Parsed API Response:', data); if (data.error) { throw new Error(data.error); } const validatedEmails = data.emails.map((email: any) => ({ id: email.id || Date.now().toString(), subject: email.subject || '(No subject)', from: email.from || '', fromName: email.fromName || email.from?.split('@')[0] || 'Unknown', date: email.date || new Date().toISOString(), read: !!email.read, starred: !!email.starred, folder: email.folder || 'INBOX' })); console.log('Processed emails:', validatedEmails); setEmails(validatedEmails); setMailUrl(data.mailUrl || 'https://espace.slm-lab.net/apps/mail/'); setError(null); } catch (err) { console.error('Fetch error:', err); setError(err instanceof Error ? err.message : 'Error fetching emails'); setEmails([]); } finally { setLoading(false); setRefreshing(false); } }; // Helper functions to parse email addresses const extractSenderName = (from: string): string => { if (!from) return 'Unknown'; const match = from.match(/^([^<]+)?/); if (match && match[1]) { return match[1].trim().replace(/"/g, ''); } return from; }; const extractEmailAddress = (from: string): string => { if (!from) return ''; const match = from.match(/<([^>]+)>/); if (match && match[1]) { return match[1]; } return from; }; // Initial fetch useEffect(() => { if (status === 'authenticated') { fetchEmails(); } }, [status]); // Auto-refresh every 5 minutes useEffect(() => { if (status !== 'authenticated') return; const interval = setInterval(() => { fetchEmails(true); }, 5 * 60 * 1000); return () => clearInterval(interval); }, [status]); const formatDate = (dateString: string) => { try { const date = new Date(dateString); return formatDistance(date, new Date(), { addSuffix: true, locale: fr }); } catch (err) { console.error('Error formatting date:', err); return dateString; } }; if (status === 'loading' || loading) { return (
Mail
); } return (
Mail
{error ? (

{error}

) : (
{emails.length === 0 ? (

{loading ? 'Loading emails...' : 'No unread emails'}

) : ( emails.map((email) => (
router.push('/mail')} >
{email.fromName || email.from}
{!email.read && } {formatDate(email.date)}

{email.subject}

)) )}
)}
); }