Neah/app/courrier/page.tsx
2025-04-25 09:25:04 +02:00

1545 lines
52 KiB
TypeScript

'use client';
import { useEffect, useState, useMemo, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import {
MoreVertical, Settings, Plus as PlusIcon, Trash2, Edit, Mail,
Inbox, Send, Star, Trash, Plus, ChevronLeft, ChevronRight,
Search, ChevronDown, Folder, ChevronUp, Reply, Forward, ReplyAll,
MoreHorizontal, FolderOpen, X, Paperclip, MessageSquare, Copy, EyeOff,
AlertOctagon, Archive, RefreshCw
} from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useSession } from 'next-auth/react';
import DOMPurify from 'isomorphic-dompurify';
import ComposeEmail from '@/components/ComposeEmail';
import { decodeEmail, cleanHtml } from '@/lib/mail-parser-wrapper';
import { Attachment as MailParserAttachment } from 'mailparser';
export interface Account {
id: number;
name: string;
email: string;
color: string;
folders?: string[];
}
export interface Email {
id: number;
accountId: number;
from: string;
fromName: string;
to: string;
subject: string;
body: string;
date: string;
read: boolean;
starred: boolean;
folder: string;
cc?: string;
bcc?: string;
flags?: string[];
raw: string;
}
interface Attachment {
name: string;
type: string;
content: string;
encoding: string;
}
interface ParsedEmailContent {
headers: string;
body: string;
html?: string;
text?: string;
attachments?: Array<{
filename: string;
content: string;
contentType: string;
}>;
}
interface ParsedEmailMetadata {
subject: string;
from: string;
to: string;
date: string;
contentType: string;
text: string | null;
html: string | null;
raw: {
headers: string;
body: string;
};
}
function splitEmailHeadersAndBody(emailBody: string): { headers: string; body: string } {
const [headers, ...bodyParts] = emailBody.split('\r\n\r\n');
return {
headers: headers || '',
body: bodyParts.join('\r\n\r\n')
};
}
function EmailContent({ email }: { email: Email }) {
const [content, setContent] = useState<React.ReactNode>(null);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
let mounted = true;
async function loadContent() {
if (!email) return;
setIsLoading(true);
try {
if (!email.body) {
if (mounted) {
setContent(<div className="text-gray-500">No content available</div>);
setIsLoading(false);
}
return;
}
const formattedEmail = email.body.trim();
if (!formattedEmail) {
if (mounted) {
setContent(<div className="text-gray-500">No content available</div>);
setIsLoading(false);
}
return;
}
const parsedEmail = await decodeEmail(formattedEmail);
if (mounted) {
if (parsedEmail.html) {
setContent(
<div
className="email-content prose prose-sm max-w-none dark:prose-invert"
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(parsedEmail.html) }}
/>
);
} else if (parsedEmail.text) {
setContent(
<div className="email-content whitespace-pre-wrap">
{parsedEmail.text}
</div>
);
} else {
setContent(<div className="text-gray-500">No content available</div>);
}
setError(null);
setIsLoading(false);
}
} catch (err) {
console.error('Error rendering email content:', err);
if (mounted) {
setError('Error rendering email content. Please try again.');
setContent(null);
setIsLoading(false);
}
}
}
loadContent();
return () => {
mounted = false;
};
}, [email?.body]);
if (isLoading) {
return (
<div className="flex items-center justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
if (error) {
return <div className="text-red-500">{error}</div>;
}
return content || <div className="text-gray-500">No content available</div>;
}
function renderEmailContent(email: Email) {
return <EmailContent email={email} />;
}
function renderAttachments(attachments: MailParserAttachment[]) {
if (!attachments.length) return null;
return (
<div className="mt-4 border-t border-gray-200 pt-4">
<h3 className="text-sm font-medium text-gray-900 mb-2">Attachments</h3>
<div className="space-y-2">
{attachments.map((attachment, index) => (
<div key={index} className="flex items-center gap-2 p-2 bg-gray-50 rounded">
<Paperclip className="h-4 w-4 text-gray-400" />
<span className="text-sm text-gray-600">{attachment.filename || 'unnamed_attachment'}</span>
<span className="text-xs text-gray-400">
{attachment.size ? `(${Math.round(attachment.size / 1024)} KB)` : ''}
</span>
</div>
))}
</div>
</div>
);
}
// Define the exact folder names from IMAP
type MailFolder = string;
// Map IMAP folders to sidebar items with icons
const getFolderIcon = (folder: string) => {
switch (folder.toLowerCase()) {
case 'inbox':
return Inbox;
case 'sent':
return Send;
case 'drafts':
return Edit;
case 'trash':
return Trash;
case 'spam':
return AlertOctagon;
case 'archive':
case 'archives':
return Archive;
default:
return Folder;
}
};
// Initial sidebar items - only INBOX
const initialSidebarItems = [
{
view: 'INBOX' as MailFolder,
label: 'Inbox',
icon: Inbox,
folder: 'INBOX'
}
];
function formatDate(date: Date | null): string {
if (!date) return '';
return new Intl.DateTimeFormat('fr-FR', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(date);
}
function ReplyContent({ email, type }: { email: Email; type: 'reply' | 'reply-all' | 'forward' }) {
const [content, setContent] = useState<string>('');
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let mounted = true;
async function loadReplyContent() {
try {
if (!email.body) {
if (mounted) setContent('');
return;
}
const decoded = await decodeEmail(email.body);
if (mounted) {
let formattedContent = '';
if (type === 'forward') {
formattedContent = `
<div class="forwarded-message">
<p>---------- Forwarded message ---------</p>
<p>From: ${decoded.from || ''}</p>
<p>Date: ${formatDate(decoded.date)}</p>
<p>Subject: ${decoded.subject || ''}</p>
<p>To: ${decoded.to || ''}</p>
<br>
${decoded.html || `<pre>${decoded.text || ''}</pre>`}
</div>
`;
} else {
formattedContent = `
<div class="quoted-message">
<p>On ${formatDate(decoded.date)}, ${decoded.from || ''} wrote:</p>
<blockquote>
${decoded.html || `<pre>${decoded.text || ''}</pre>`}
</blockquote>
</div>
`;
}
setContent(formattedContent);
setError(null);
}
} catch (err) {
console.error('Error generating reply body:', err);
if (mounted) {
setError('Error generating reply content. Please try again.');
setContent('');
}
}
}
loadReplyContent();
return () => {
mounted = false;
};
}, [email.body, type]);
if (error) {
return <div className="text-red-500">{error}</div>;
}
return <div dangerouslySetInnerHTML={{ __html: content }} />;
}
// Update the getReplyBody function to use the new component
function getReplyBody(email: Email, type: 'reply' | 'reply-all' | 'forward' = 'reply') {
return <ReplyContent email={email} type={type} />;
}
function EmailPreview({ email }: { email: Email }) {
const [preview, setPreview] = useState<string>('');
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
let mounted = true;
async function loadPreview() {
if (!email?.body) {
if (mounted) setPreview('No content available');
return;
}
setIsLoading(true);
try {
const decoded = await decodeEmail(email.body);
if (mounted) {
if (decoded.text) {
setPreview(decoded.text.substring(0, 150) + '...');
} else if (decoded.html) {
const cleanText = decoded.html.replace(/<[^>]*>/g, ' ').trim();
setPreview(cleanText.substring(0, 150) + '...');
} else {
setPreview('No preview available');
}
setError(null);
}
} catch (err) {
console.error('Error generating email preview:', err);
if (mounted) {
setError('Error generating preview');
setPreview('');
}
} finally {
if (mounted) setIsLoading(false);
}
}
loadPreview();
return () => {
mounted = false;
};
}, [email?.body]);
if (isLoading) {
return <span className="text-gray-400">Loading preview...</span>;
}
if (error) {
return <span className="text-red-500 text-xs">{error}</span>;
}
return <span className="text-xs text-gray-500 line-clamp-2">{preview}</span>;
}
// Update the generateEmailPreview function to use the new component
function generateEmailPreview(email: Email) {
return <EmailPreview email={email} />;
}
export default function CourrierPage() {
const router = useRouter();
const { data: session } = useSession();
const [loading, setLoading] = useState(true);
const [accounts, setAccounts] = useState<Account[]>([
{ id: 0, name: 'All', email: '', color: 'bg-gray-500' },
{ id: 1, name: 'Mail', email: 'alma@governance-labs.org', color: 'bg-blue-500' }
]);
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null);
const [currentView, setCurrentView] = useState<MailFolder>('INBOX');
const [showCompose, setShowCompose] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
const [showBulkActions, setShowBulkActions] = useState(false);
const [showBcc, setShowBcc] = useState(false);
const [emails, setEmails] = useState<Email[]>([]);
const [error, setError] = useState<string | null>(null);
const [composeSubject, setComposeSubject] = useState('');
const [composeTo, setComposeTo] = useState('');
const [composeCc, setComposeCc] = useState('');
const [composeBcc, setComposeBcc] = useState('');
const [composeBody, setComposeBody] = useState('');
const [selectedEmail, setSelectedEmail] = useState<Email | null>(null);
const [sidebarOpen, setSidebarOpen] = useState(true);
const [foldersOpen, setFoldersOpen] = useState(true);
const [showSettings, setShowSettings] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [composeOpen, setComposeOpen] = useState(false);
const [accountsDropdownOpen, setAccountsDropdownOpen] = useState(false);
const [foldersDropdownOpen, setFoldersDropdownOpen] = useState(false);
const [showAccountActions, setShowAccountActions] = useState<number | null>(null);
const [showEmailActions, setShowEmailActions] = useState(false);
const [deleteType, setDeleteType] = useState<'email' | 'emails' | 'account'>('email');
const [itemToDelete, setItemToDelete] = useState<number | null>(null);
const [showCc, setShowCc] = useState(false);
const [contentLoading, setContentLoading] = useState(false);
const [attachments, setAttachments] = useState<Attachment[]>([]);
const [folders, setFolders] = useState<string[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [availableFolders, setAvailableFolders] = useState<string[]>([]);
const [sidebarItems, setSidebarItems] = useState(initialSidebarItems);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const [isLoadingInitial, setIsLoadingInitial] = useState(true);
const [isLoadingSearch, setIsLoadingSearch] = useState(false);
const [isLoadingCompose, setIsLoadingCompose] = useState(false);
const [isLoadingReply, setIsLoadingReply] = useState(false);
const [isLoadingForward, setIsLoadingForward] = useState(false);
const [isLoadingDelete, setIsLoadingDelete] = useState(false);
const [isLoadingMove, setIsLoadingMove] = useState(false);
const [isLoadingStar, setIsLoadingStar] = useState(false);
const [isLoadingUnstar, setIsLoadingUnstar] = useState(false);
const [isLoadingMarkRead, setIsLoadingMarkRead] = useState(false);
const [isLoadingMarkUnread, setIsLoadingMarkUnread] = useState(false);
const [isLoadingRefresh, setIsLoadingRefresh] = useState(false);
const emailsPerPage = 20;
const [isSearching, setIsSearching] = useState(false);
const [searchResults, setSearchResults] = useState<Email[]>([]);
const [showSearchResults, setShowSearchResults] = useState(false);
const [isComposing, setIsComposing] = useState(false);
const [composeEmail, setComposeEmail] = useState({
to: '',
subject: '',
body: '',
});
const [isSending, setIsSending] = useState(false);
const [isReplying, setIsReplying] = useState(false);
const [isForwarding, setIsForwarding] = useState(false);
const [replyToEmail, setReplyToEmail] = useState<Email | null>(null);
const [forwardEmail, setForwardEmail] = useState<Email | null>(null);
const [replyBody, setReplyBody] = useState('');
const [forwardBody, setForwardBody] = useState('');
const [replyAttachments, setReplyAttachments] = useState<File[]>([]);
const [forwardAttachments, setForwardAttachments] = useState<File[]>([]);
const [isSendingReply, setIsSendingReply] = useState(false);
const [isSendingForward, setIsSendingForward] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isMoving, setIsMoving] = useState(false);
const [isStarring, setIsStarring] = useState(false);
const [isUnstarring, setIsUnstarring] = useState(false);
const [isMarkingRead, setIsMarkingRead] = useState(false);
const [isMarkingUnread, setIsMarkingUnread] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const composeBodyRef = useRef<HTMLDivElement>(null);
const [originalEmail, setOriginalEmail] = useState<{
content: string;
type: 'reply' | 'reply-all' | 'forward';
} | null>(null);
// Debug logging for email distribution
useEffect(() => {
const emailsByFolder = emails.reduce((acc, email) => {
acc[email.folder] = (acc[email.folder] || 0) + 1;
return acc;
}, {} as Record<string, number>);
console.log('Emails by folder:', emailsByFolder);
console.log('Current view:', currentView);
}, [emails, currentView]);
// Move getSelectedEmail inside the component
const getSelectedEmail = () => {
return emails.find(email => email.id === selectedEmail?.id);
};
// Check for stored credentials
useEffect(() => {
const checkCredentials = async () => {
try {
console.log('Checking for stored credentials...');
const response = await fetch('/api/courrier');
if (!response.ok) {
const errorData = await response.json();
console.log('API response error:', errorData);
if (errorData.error === 'No stored credentials found') {
console.log('No credentials found, redirecting to login...');
router.push('/courrier/login');
return;
}
throw new Error(errorData.error || 'Failed to check credentials');
}
console.log('Credentials verified, loading emails...');
setLoading(false);
loadEmails();
} catch (err) {
console.error('Error checking credentials:', err);
setError(err instanceof Error ? err.message : 'Failed to check credentials');
setLoading(false);
}
};
checkCredentials();
}, [router]);
// Update the loadEmails function
const loadEmails = async (isLoadMore = false) => {
try {
if (isLoadMore) {
setIsLoadingMore(true);
} else {
setLoading(true);
}
setError(null);
const response = await fetch(`/api/courrier?folder=${encodeURIComponent(currentView)}&page=${page}&limit=${emailsPerPage}`);
if (!response.ok) {
throw new Error('Failed to load emails');
}
const data = await response.json();
// Get available folders from the API response
if (data.folders) {
setAvailableFolders(data.folders);
}
// Process emails keeping exact folder names and sort by date
const processedEmails = (data.emails || [])
.map((email: any) => ({
id: Number(email.id),
accountId: 1,
from: email.from || '',
fromName: email.fromName || email.from?.split('@')[0] || '',
to: email.to || '',
subject: email.subject || '(No subject)',
body: email.body || '',
date: email.date || new Date().toISOString(),
read: email.read || false,
starred: email.starred || false,
folder: email.folder || currentView,
cc: email.cc,
bcc: email.bcc,
flags: email.flags || [],
raw: email.body || ''
}));
// Sort emails by date, ensuring most recent first
const sortedEmails = processedEmails.sort((a: Email, b: Email) => {
const dateA = new Date(a.date).getTime();
const dateB = new Date(b.date).getTime();
return dateB - dateA; // Most recent first
});
// Only update unread count if we're in the Inbox folder
if (currentView === 'INBOX') {
const unreadInboxEmails = sortedEmails.filter(
(email: Email) => !email.read && email.folder === 'INBOX'
).length;
setUnreadCount(unreadInboxEmails);
}
if (isLoadMore) {
// When loading more, merge with existing emails and re-sort
setEmails(prev => {
const combined = [...prev, ...sortedEmails];
return combined.sort((a: Email, b: Email) => {
const dateA = new Date(a.date).getTime();
const dateB = new Date(b.date).getTime();
return dateB - dateA; // Most recent first
});
});
setPage(prev => prev + 1);
} else {
// For initial load or refresh, just use the sorted emails
setEmails(sortedEmails);
setPage(1);
}
// Update hasMore based on API response
setHasMore(data.hasMore || false);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load emails');
} finally {
setLoading(false);
setIsLoadingMore(false);
}
};
// Add an effect to reload emails when the view changes
useEffect(() => {
setPage(1); // Reset page when view changes
setHasMore(true);
loadEmails();
}, [currentView]);
// Get account color
const getAccountColor = (accountId: number) => {
const account = accounts.find(acc => acc.id === accountId);
return account ? account.color : 'bg-gray-500';
};
// Update handleEmailSelect to set selectedEmail correctly
const handleEmailSelect = async (emailId: number) => {
const email = emails.find(e => e.id === emailId);
if (!email) {
return;
}
try {
// Set the selected email first to show preview immediately
setSelectedEmail(email);
setContentLoading(true);
// Fetch the full email content
const response = await fetch(`/api/mail/${emailId}`);
if (!response.ok) {
throw new Error('Failed to fetch full email content');
}
const fullEmail = await response.json();
// Update the email in the list and selected email with full content
setEmails(prevEmails => prevEmails.map(email =>
email.id === emailId
? { ...email, body: fullEmail.body || email.body }
: email
));
setSelectedEmail(prev => prev ? { ...prev, body: fullEmail.body || prev.body } : prev);
setContentLoading(false);
// Try to mark as read in the background
try {
const markReadResponse = await fetch(`/api/mail/mark-read`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
emailId,
isRead: true,
}),
});
if (markReadResponse.ok) {
// Only update the emails list if the API call was successful
setEmails((prevEmails: Email[]) =>
prevEmails.map((email: Email): Email =>
email.id === emailId
? { ...email, read: true }
: email
)
);
} else {
console.error('Failed to mark email as read:', await markReadResponse.text());
}
} catch (error) {
console.error('Error marking email as read:', error);
}
} catch (error) {
console.error('Error fetching email content:', error);
setContentLoading(false);
}
};
// Add these improved handlers
const handleEmailCheckbox = (e: React.ChangeEvent<HTMLInputElement>, emailId: number) => {
e.stopPropagation();
if (e.target.checked) {
setSelectedEmails([...selectedEmails, emailId.toString()]);
} else {
setSelectedEmails(selectedEmails.filter(id => id !== emailId.toString()));
}
};
// Handles marking an individual email as read/unread
const handleMarkAsRead = (emailId: string, isRead: boolean) => {
setEmails(emails.map(email =>
email.id.toString() === emailId ? { ...email, read: isRead } : email
));
};
// Handles bulk actions for selected emails
const handleBulkAction = async (action: 'delete' | 'mark-read' | 'mark-unread' | 'archive') => {
if (action === 'delete') {
setDeleteType('emails');
setShowDeleteConfirm(true);
return;
}
try {
const response = await fetch('/api/courrier/bulk-actions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
emailIds: selectedEmails,
action: action
}),
});
if (!response.ok) {
throw new Error('Failed to perform bulk action');
}
// Update local state based on the action
setEmails(emails.map(email => {
if (selectedEmails.includes(email.id.toString())) {
switch (action) {
case 'mark-read':
return { ...email, read: true };
case 'mark-unread':
return { ...email, read: false };
case 'archive':
return { ...email, folder: 'Archive' };
default:
return email;
}
}
return email;
}));
// Clear selection after successful action
setSelectedEmails([]);
} catch (error) {
console.error('Error performing bulk action:', error);
alert('Failed to perform bulk action. Please try again.');
}
};
// Add handleDeleteConfirm function
const handleDeleteConfirm = async () => {
try {
const response = await fetch('/api/courrier/bulk-actions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
emailIds: selectedEmails,
action: 'delete'
}),
});
if (!response.ok) {
throw new Error('Failed to delete emails');
}
// Remove deleted emails from state
setEmails(emails.filter(email => !selectedEmails.includes(email.id.toString())));
setSelectedEmails([]);
} catch (error) {
console.error('Error deleting emails:', error);
alert('Failed to delete emails. Please try again.');
} finally {
setShowDeleteConfirm(false);
}
};
// Add infinite scroll handler
const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
const target = e.currentTarget;
if (
target.scrollHeight - target.scrollTop === target.clientHeight &&
!isLoadingMore &&
hasMore
) {
setPage(prev => prev + 1);
loadEmails(true);
}
}, [isLoadingMore, hasMore]);
// Sort emails by date (most recent first)
const sortedEmails = useMemo(() => {
return [...emails].sort((a, b) => {
return new Date(b.date).getTime() - new Date(a.date).getTime();
});
}, [emails]);
const toggleSelectAll = () => {
if (selectedEmails.length === emails.length) {
setSelectedEmails([]);
} else {
setSelectedEmails(emails.map(email => email.id.toString()));
}
};
// Update filtered emails to use sortedEmails
const filteredEmails = useMemo(() => {
if (!searchQuery) return sortedEmails;
const query = searchQuery.toLowerCase();
return sortedEmails.filter(email =>
email.subject.toLowerCase().includes(query) ||
email.from.toLowerCase().includes(query) ||
email.to.toLowerCase().includes(query) ||
email.body.toLowerCase().includes(query)
);
}, [sortedEmails, searchQuery]);
// Update the email list to use filtered emails
const renderEmailList = () => (
<div className="w-[320px] bg-white/95 backdrop-blur-sm border-r border-gray-100 flex flex-col">
{renderEmailListHeader()}
{renderBulkActionsToolbar()}
<div
className="flex-1 overflow-y-auto"
onScroll={handleScroll}
>
{loading ? (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
) : filteredEmails.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64">
<Mail className="h-8 w-8 text-gray-400 mb-2" />
<p className="text-gray-500 text-sm">
{searchQuery ? 'No emails match your search' : 'No emails in this folder'}
</p>
</div>
) : (
<div className="divide-y divide-gray-100">
{filteredEmails.map((email) => renderEmailListItem(email))}
{isLoadingMore && (
<div className="flex items-center justify-center p-4">
<div className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-blue-500"></div>
</div>
)}
</div>
)}
</div>
</div>
);
// Update the email count in the header to show filtered count
const renderEmailListHeader = () => (
<div className="border-b border-gray-100">
<div className="px-4 py-3">
<div className="relative">
<Search className="absolute left-2 top-2 h-4 w-4 text-gray-400" />
<Input
type="search"
placeholder="Search in folder..."
className="pl-8 h-8 bg-gray-50"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
</div>
<div className="flex items-center justify-between px-4 h-10">
<div className="flex items-center gap-2">
<Checkbox
checked={filteredEmails.length > 0 && selectedEmails.length === filteredEmails.length}
onCheckedChange={toggleSelectAll}
className="mt-0.5"
/>
<h2 className="text-base font-semibold text-gray-900">
{currentView.charAt(0).toUpperCase() + currentView.slice(1).toLowerCase()}
</h2>
</div>
<span className="text-sm text-gray-600">
{searchQuery ? `${filteredEmails.length} of ${emails.length} emails` : `${emails.length} emails`}
</span>
</div>
</div>
);
// Update the bulk actions toolbar to include confirmation dialog
const renderBulkActionsToolbar = () => {
if (selectedEmails.length === 0) return null;
return (
<div className="bg-white border-b border-gray-100 px-4 py-2">
<div className="flex items-center gap-2 mb-2">
<span className="text-sm text-gray-600">
{selectedEmails.length} selected
</span>
</div>
<div className="flex items-center gap-1.5">
<Button
variant="ghost"
size="sm"
className="text-gray-600 hover:text-gray-900 h-8 px-2"
onClick={() => {
const allSelectedRead = selectedEmails.every(id =>
emails.find(email => email.id.toString() === id)?.read
);
handleBulkAction(allSelectedRead ? 'mark-unread' : 'mark-read');
}}
>
<EyeOff className="h-4 w-4 mr-1" />
<span className="text-sm">
{selectedEmails.every(id =>
emails.find(email => email.id.toString() === id)?.read
) ? 'Unread' : 'Read'}
</span>
</Button>
<Button
variant="ghost"
size="sm"
className="text-gray-600 hover:text-gray-900 h-8 px-2"
onClick={() => handleBulkAction('archive')}
>
<Archive className="h-4 w-4 mr-1" />
<span className="text-sm">Archive</span>
</Button>
<Button
variant="ghost"
size="sm"
className="text-red-600 hover:text-red-700 h-8 px-2"
onClick={() => handleBulkAction('delete')}
>
<Trash2 className="h-4 w-4 mr-1" />
<span className="text-sm">Delete</span>
</Button>
</div>
</div>
);
};
// Keep only one renderEmailListWrapper function that includes both panels
const renderEmailListWrapper = () => (
<div className="flex-1 flex overflow-hidden">
{/* Email list panel */}
{renderEmailList()}
{/* Preview panel - will automatically take remaining space */}
<div className="flex-1 bg-white/95 backdrop-blur-sm flex flex-col">
{selectedEmail ? (
<>
{/* Email actions header */}
<div className="flex-none px-4 py-3 border-b border-gray-100">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2 min-w-0 flex-1">
<Button
variant="ghost"
size="icon"
onClick={() => setSelectedEmail(null)}
className="md:hidden flex-shrink-0"
>
<ChevronLeft className="h-5 w-5" />
</Button>
<div className="min-w-0 max-w-[500px]">
<h2 className="text-lg font-semibold text-gray-900 truncate">
{selectedEmail.subject}
</h2>
</div>
</div>
<div className="flex items-center gap-1 flex-shrink-0 ml-auto">
<div className="flex items-center border-l border-gray-200 pl-4">
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-gray-900 h-9 w-9"
onClick={() => handleReply('reply')}
>
<Reply className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-gray-900 h-9 w-9"
onClick={() => handleReply('reply-all')}
>
<ReplyAll className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-gray-900 h-9 w-9"
onClick={() => handleReply('forward')}
>
<Forward className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-gray-900 h-9 w-9"
onClick={(e) => toggleStarred(selectedEmail.id, e)}
>
<Star className={`h-4 w-4 ${selectedEmail.starred ? 'fill-yellow-400 text-yellow-400' : ''}`} />
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-gray-900 h-9 w-9"
onClick={() => {/* Add to folder logic */}}
>
<FolderOpen className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
{/* Scrollable content area */}
<ScrollArea className="flex-1 p-6">
<div className="flex items-center gap-4 mb-6">
<Avatar className="h-10 w-10">
<AvatarFallback>
{selectedEmail.fromName?.charAt(0) || selectedEmail.from.charAt(0)}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<p className="font-medium text-gray-900">
{selectedEmail.fromName} <span className="text-gray-500">&lt;{selectedEmail.from}&gt;</span>
</p>
<p className="text-sm text-gray-500">
to {selectedEmail.to}
</p>
{selectedEmail.cc && (
<p className="text-sm text-gray-500">
cc {selectedEmail.cc}
</p>
)}
</div>
<div className="text-sm text-gray-500 whitespace-nowrap">
{formatDate(new Date(selectedEmail.date))}
</div>
</div>
<div className="prose max-w-none">
{renderEmailContent(selectedEmail)}
</div>
</ScrollArea>
</>
) : (
<div className="flex flex-col items-center justify-center h-full">
<Mail className="h-12 w-12 text-gray-400 mb-4" />
<p className="text-gray-500">Select an email to view its contents</p>
</div>
)}
</div>
</div>
);
// Update sidebar items when available folders change
useEffect(() => {
if (availableFolders.length > 0) {
const newItems = [
...initialSidebarItems,
...availableFolders
.filter(folder => !['INBOX'].includes(folder)) // Exclude folders already in initial items
.map(folder => ({
view: folder as MailFolder,
label: folder.charAt(0).toUpperCase() + folder.slice(1).toLowerCase(),
icon: getFolderIcon(folder),
folder: folder
}))
];
setSidebarItems(newItems);
}
}, [availableFolders]);
// Update the email list item to match header checkbox alignment
const renderEmailListItem = (email: Email) => {
return (
<div
key={email.id}
className={`flex items-center gap-3 px-4 py-2 hover:bg-gray-50/80 cursor-pointer ${
selectedEmail?.id === email.id ? 'bg-blue-50/50' : ''
} ${!email.read ? 'bg-blue-50/20' : ''}`}
onClick={() => handleEmailSelect(email.id)}
>
<Checkbox
checked={selectedEmails.includes(email.id.toString())}
onCheckedChange={(checked) => {
const e = { target: { checked }, stopPropagation: () => {} } as React.ChangeEvent<HTMLInputElement>;
handleEmailCheckbox(e, email.id);
}}
onClick={(e) => e.stopPropagation()}
className="mt-0.5"
/>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<span className={`text-sm truncate ${!email.read ? 'font-semibold text-gray-900' : 'text-gray-600'}`}>
{email.fromName || email.from}
</span>
</div>
<span className="text-xs text-gray-500 whitespace-nowrap">
{formatDate(new Date(email.date))}
</span>
</div>
<h3 className="text-sm text-gray-900 truncate">
{email.subject || '(No subject)'}
</h3>
<div className="text-xs text-gray-500 line-clamp-2">
{generateEmailPreview(email)}
</div>
</div>
</div>
);
};
const handleMailboxChange = async (newMailbox: string) => {
setCurrentView(newMailbox);
setSelectedEmails([]);
setSearchQuery('');
setEmails([]);
setLoading(true);
setError(null);
setHasMore(true);
setPage(1);
try {
// Optimize the request by adding a timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
const response = await fetch(`/api/courrier?folder=${encodeURIComponent(newMailbox)}&page=1&limit=${emailsPerPage}`, {
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error('Failed to fetch emails');
}
const data = await response.json();
// Process emails more efficiently
const processedEmails = data.emails.map((email: any) => ({
id: Number(email.id),
accountId: 1,
from: email.from || '',
fromName: email.from?.split('@')[0] || '',
to: email.to || '',
subject: email.subject || '(No subject)',
body: email.body || '',
date: email.date || new Date().toISOString(),
read: email.read || false,
starred: email.starred || false,
folder: email.folder || newMailbox,
cc: email.cc,
bcc: email.bcc,
flags: email.flags || [],
raw: email.body || ''
}));
setEmails(processedEmails);
setHasMore(processedEmails.length === emailsPerPage);
// Only update unread count if we're in the Inbox folder
if (newMailbox === 'INBOX') {
const unreadInboxEmails = processedEmails.filter(
(email: Email) => !email.read && email.folder === 'INBOX'
).length;
setUnreadCount(unreadInboxEmails);
}
} catch (error) {
console.error('Error fetching emails:', error);
setError(error instanceof Error ? error.message : 'Failed to fetch emails');
} finally {
setLoading(false);
}
};
// Add back the renderSidebarNav function
const renderSidebarNav = () => (
<nav className="p-3">
<ul className="space-y-0.5 px-2">
{sidebarItems.map((item) => (
<li key={item.view}>
<Button
variant={currentView === item.view ? 'secondary' : 'ghost'}
className={`w-full justify-start py-2 ${
currentView === item.view ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:text-gray-900'
}`}
onClick={() => {
setCurrentView(item.view);
setSelectedEmail(null);
}}
>
<div className="flex items-center justify-between w-full">
<div className="flex items-center">
<item.icon className="h-4 w-4 mr-2" />
<span>{item.label}</span>
</div>
{item.view === 'INBOX' && unreadCount > 0 && (
<span className="ml-auto bg-blue-600 text-white text-xs px-2 py-0.5 rounded-full">
{unreadCount}
</span>
)}
</div>
</Button>
</li>
))}
</ul>
</nav>
);
// Add back the handleReply function
const handleReply = async (type: 'reply' | 'reply-all' | 'forward') => {
if (!selectedEmail) return;
try {
// Get the decoded content first
const decoded = await decodeEmail(selectedEmail.body);
// Set up the reply details
const getReplyTo = () => {
if (type === 'forward') return '';
return selectedEmail.from;
};
const getReplyCc = () => {
if (type !== 'reply-all') return '';
return selectedEmail.cc || '';
};
const getReplySubject = () => {
const subject = selectedEmail.subject || '';
if (type === 'forward') {
return subject.startsWith('Fwd:') ? subject : `Fwd: ${subject}`;
}
return subject.startsWith('Re:') ? subject : `Re: ${subject}`;
};
// Create the appropriate email content based on type
let formattedContent = '';
if (type === 'forward') {
formattedContent = `
<div style="min-height: 100px;">
<br/>
<div style="border-top: 1px solid #e5e7eb; margin-top: 20px; padding-top: 10px; color: #666;">
---------- Forwarded message ---------<br/>
From: ${selectedEmail.from}<br/>
Date: ${new Date(selectedEmail.date).toLocaleString()}<br/>
Subject: ${selectedEmail.subject}<br/>
To: ${selectedEmail.to}<br/>
${selectedEmail.cc ? `Cc: ${selectedEmail.cc}<br/>` : ''}
<br/>
<div style="margin-top: 10px;">
${decoded.html || decoded.text || ''}
</div>
</div>
</div>
`;
} else {
// For reply and reply-all
formattedContent = `
<div style="min-height: 100px;">
<br/>
<div style="border-left: 2px solid #e5e7eb; margin: 10px 0; padding-left: 10px; color: #666;">
On ${new Date(selectedEmail.date).toLocaleString()}, ${selectedEmail.from} wrote:<br/>
<br/>
${decoded.html || decoded.text || ''}
</div>
</div>
`;
}
// Update the compose form
setComposeTo(getReplyTo());
setComposeCc(getReplyCc());
setComposeSubject(getReplySubject());
setComposeBody(formattedContent);
setComposeBcc('');
setShowCompose(true);
setShowCc(type === 'reply-all');
setShowBcc(false);
setAttachments([]);
} catch (error) {
console.error('Error preparing reply:', error);
}
};
// Add back the toggleStarred function
const toggleStarred = async (emailId: number, e?: React.MouseEvent) => {
if (e) {
e.stopPropagation();
}
const email = emails.find(e => e.id === emailId);
if (!email) return;
try {
const response = await fetch('/api/courrier/toggle-star', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ emailId, starred: !email.starred }),
});
if (!response.ok) {
throw new Error('Failed to toggle star');
}
// Update email in state
setEmails(emails.map(e =>
e.id === emailId ? { ...e, starred: !e.starred } : e
));
} catch (error) {
console.error('Error toggling star:', error);
}
};
// Add back the handleSend function
const handleSend = async () => {
if (!composeTo) {
alert('Please specify at least one recipient');
return;
}
try {
const response = await fetch('/api/courrier/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: composeTo,
cc: composeCc,
bcc: composeBcc,
subject: composeSubject,
body: composeBody,
attachments: attachments,
}),
});
const data = await response.json();
if (!response.ok) {
if (data.error === 'Attachment size limit exceeded') {
alert(`Error: ${data.error}\nThe following files are too large:\n${data.details.oversizedFiles.join('\n')}`);
} else {
alert(`Error sending email: ${data.error}`);
}
return;
}
// Clear compose form and close modal
setComposeTo('');
setComposeCc('');
setComposeBcc('');
setComposeSubject('');
setComposeBody('');
setAttachments([]);
setShowCompose(false);
} catch (error) {
console.error('Error sending email:', error);
alert('Failed to send email. Please try again.');
}
};
// Add back the renderDeleteConfirmDialog function
const renderDeleteConfirmDialog = () => (
<AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Emails</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete {selectedEmails.length} selected email{selectedEmails.length > 1 ? 's' : ''}? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDeleteConfirm}>Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
if (error) {
return (
<div className="flex h-[calc(100vh-theme(spacing.12))] items-center justify-center bg-gray-100 mt-12">
<div className="text-center max-w-md mx-auto px-4">
<Mail className="h-12 w-12 mb-4 text-red-400 mx-auto" />
<p className="text-red-500 mb-4">{error}</p>
<Button
variant="outline"
onClick={() => window.location.reload()}
className="mx-auto"
>
Try Again
</Button>
</div>
</div>
);
}
return (
<>
{/* Main layout */}
<main className="w-full h-screen bg-black">
<div className="w-full h-full px-4 pt-12 pb-4">
<div className="flex h-full bg-carnet-bg">
{/* Sidebar */}
<div className={`${sidebarOpen ? 'w-60' : 'w-16'} bg-white/95 backdrop-blur-sm border-r border-gray-100 flex flex-col transition-all duration-300 ease-in-out
${mobileSidebarOpen ? 'fixed inset-y-0 left-0 z-40' : 'hidden'} md:block`}>
{/* Courrier Title */}
<div className="p-3 border-b border-gray-100">
<div className="flex items-center gap-2">
<Mail className="h-6 w-6 text-gray-600" />
<span className="text-xl font-semibold text-gray-900">COURRIER</span>
</div>
</div>
{/* Compose button and refresh button */}
<div className="p-2 border-b border-gray-100 flex items-center gap-2">
<Button
className="flex-1 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center transition-all py-1.5 text-sm"
onClick={() => {
setShowCompose(true);
setComposeTo('');
setComposeCc('');
setComposeBcc('');
setComposeSubject('');
setComposeBody('');
setShowCc(false);
setShowBcc(false);
}}
>
<div className="flex items-center gap-2">
<PlusIcon className="h-3.5 w-3.5" />
<span>Compose</span>
</div>
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => handleMailboxChange('INBOX')}
className="text-gray-600 hover:text-gray-900 hover:bg-gray-100"
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
{/* Accounts Section */}
<div className="p-3 border-b border-gray-100">
<Button
variant="ghost"
className="w-full justify-between mb-2 text-sm font-medium text-gray-500"
onClick={() => setAccountsDropdownOpen(!accountsDropdownOpen)}
>
<span>Accounts</span>
{accountsDropdownOpen ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
</Button>
{accountsDropdownOpen && (
<div className="space-y-1 pl-2">
{accounts.map(account => (
<div key={account.id} className="relative group">
<Button
variant="ghost"
className="w-full justify-between px-2 py-1.5 text-sm group"
onClick={() => setSelectedAccount(account)}
>
<div className="flex flex-col items-start">
<div className="flex items-center gap-2">
<div className={`w-2.5 h-2.5 rounded-full ${account.color}`}></div>
<span className="font-medium">{account.name}</span>
</div>
<span className="text-xs text-gray-500 ml-4">{account.email}</span>
</div>
</Button>
</div>
))}
</div>
)}
</div>
{/* Navigation */}
{renderSidebarNav()}
</div>
{/* Main content area */}
<div className="flex-1 flex overflow-hidden">
{/* Email list panel */}
{renderEmailListWrapper()}
</div>
</div>
</div>
</main>
{/* Compose Email Modal */}
<ComposeEmail
showCompose={showCompose}
setShowCompose={setShowCompose}
composeTo={composeTo}
setComposeTo={setComposeTo}
composeCc={composeCc}
setComposeCc={setComposeCc}
composeBcc={composeBcc}
setComposeBcc={setComposeBcc}
composeSubject={composeSubject}
setComposeSubject={setComposeSubject}
composeBody={composeBody}
setComposeBody={setComposeBody}
showCc={showCc}
setShowCc={setShowCc}
showBcc={showBcc}
setShowBcc={setShowBcc}
attachments={attachments}
setAttachments={setAttachments}
handleSend={handleSend}
onSend={(email) => {
console.log('Email sent:', email);
setShowCompose(false);
}}
onCancel={() => {
setShowCompose(false);
setComposeTo('');
setComposeCc('');
setComposeBcc('');
setComposeSubject('');
setComposeBody('');
setShowCc(false);
setShowBcc(false);
setAttachments([]);
}}
/>
{renderDeleteConfirmDialog()}
</>
);
}