'use client'; import { useState, useRef, useEffect } from 'react'; import { formatEmailForReplyOrForward, EmailMessage } from '@/lib/services/email-service'; import { X, Paperclip, ChevronDown, ChevronUp, SendHorizontal, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'; import { decodeEmail } from '@/lib/mail-parser-wrapper'; interface ComposeEmailProps { initialEmail?: EmailMessage | null; type?: 'new' | 'reply' | 'reply-all' | 'forward'; onClose: () => void; onSend: (emailData: { to: string; cc?: string; bcc?: string; subject: string; body: string; attachments?: Array<{ name: string; content: string; type: string; }>; }) => Promise; } export default function ComposeEmail({ initialEmail, type = 'new', onClose, onSend }: ComposeEmailProps) { // Email form state const [to, setTo] = useState(''); const [cc, setCc] = useState(''); const [bcc, setBcc] = useState(''); const [subject, setSubject] = useState(''); const [body, setBody] = useState(''); // UI state const [showCc, setShowCc] = useState(false); const [showBcc, setShowBcc] = useState(false); const [sending, setSending] = useState(false); const [attachments, setAttachments] = useState>([]); const editorRef = useRef(null); const attachmentInputRef = useRef(null); // Initialize the form when replying to or forwarding an email useEffect(() => { if (initialEmail && type !== 'new') { // If it's a forward, use the same approach as Panel 3 if (type === 'forward') { initializeForwardedEmail(); } else { // For reply/reply-all, continue using formatEmailForReplyOrForward const formattedEmail = formatEmailForReplyOrForward(initialEmail, type as 'reply' | 'reply-all'); setTo(formattedEmail.to); if (formattedEmail.cc) { setCc(formattedEmail.cc); setShowCc(true); } setSubject(formattedEmail.subject); setBody(formattedEmail.body); } // Focus editor after initializing setTimeout(() => { if (editorRef.current) { editorRef.current.focus(); // Place cursor at the beginning of the content const selection = window.getSelection(); const range = document.createRange(); range.setStart(editorRef.current, 0); range.collapse(true); selection?.removeAllRanges(); selection?.addRange(range); } }, 100); } }, [initialEmail, type]); // New function to initialize forwarded email using same approach as Panel 3 const initializeForwardedEmail = async () => { if (!initialEmail || !initialEmail.content) { console.error('No email content available for forwarding'); setBody('
No content available
'); return; } try { setSending(true); // Use sending state to show loading // Use the same decoding approach as Panel 3 const decoded = await decodeEmail(initialEmail.content); // Format subject with Fwd: prefix if needed const cleanSubject = initialEmail.subject.replace(/^(Fwd|FW|Forward):\s*/i, '').trim(); const formattedSubject = initialEmail.subject.match(/^(Fwd|FW|Forward):/i) ? initialEmail.subject : `Fwd: ${cleanSubject}`; setSubject(formattedSubject); // Format date for the forwarded message header const formatDate = (date: Date | null): string => { if (!date) return ''; return date.toLocaleString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }; // Create the same forwarded message format as Panel 3 const formattedContent = `

---------- Forwarded message ---------

From: ${decoded.from || ''}

Date: ${formatDate(decoded.date)}

Subject: ${decoded.subject || ''}

To: ${decoded.to || ''}

${decoded.html || `
${decoded.text || ''}
`}
`; setBody(formattedContent); } catch (error) { console.error('Error initializing forwarded email:', error); setBody('
Error loading forwarded content
'); } finally { setSending(false); } }; // Handle attachment selection const handleAttachmentClick = () => { attachmentInputRef.current?.click(); }; // Process selected files const handleFileSelection = async (e: React.ChangeEvent) => { const files = e.target.files; if (!files || files.length === 0) return; // Convert selected files to attachments const newAttachments = Array.from(files).map(file => ({ file, uploading: true })); // Read files as data URLs for (const file of files) { const reader = new FileReader(); reader.onload = (event) => { const content = event.target?.result as string; setAttachments(current => [ ...current, { name: file.name, content: content.split(',')[1], // Remove data:mime/type;base64, prefix type: file.type } ]); }; reader.readAsDataURL(file); } // Reset file input if (e.target) { e.target.value = ''; } }; // Remove attachment const removeAttachment = (index: number) => { setAttachments(current => current.filter((_, i) => i !== index)); }; // Send the email const handleSend = async () => { if (!to) { alert('Please specify at least one recipient'); return; } try { setSending(true); await onSend({ to, cc: cc || undefined, bcc: bcc || undefined, subject, body: editorRef.current?.innerHTML || body, attachments }); onClose(); } catch (error) { console.error('Error sending email:', error); alert('Failed to send email. Please try again.'); } finally { setSending(false); } }; // Handle editor input const handleEditorInput = (e: React.FormEvent) => { // Store the HTML content for use in the send function setBody(e.currentTarget.innerHTML); }; return (
{type === 'new' ? 'New Message' : type === 'reply' ? 'Reply' : type === 'reply-all' ? 'Reply All' : 'Forward'}
{/* Email header fields */}
To: setTo(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="recipient@example.com" />
{showCc && (
Cc: setCc(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="cc@example.com" />
)} {showBcc && (
Bcc: setBcc(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="bcc@example.com" />
)} {/* CC/BCC controls */}
Subject: setSubject(e.target.value)} className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0" placeholder="Subject" />
{/* Email body editor */}
{/* Attachments list */} {attachments.length > 0 && (
Attachments:
{attachments.map((attachment, index) => (
{attachment.name}
))}
)}
); }