'use client'; import { useRef, useEffect, useState } from 'react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Paperclip, X } from 'lucide-react'; import { Textarea } from '@/components/ui/textarea'; import { decodeComposeContent, encodeComposeContent } from '@/lib/compose-mime-decoder'; import { Email } from '@/app/courrier/page'; import mime from 'mime'; interface ComposeEmailProps { showCompose: boolean; setShowCompose: (show: boolean) => void; composeTo: string; setComposeTo: (to: string) => void; composeCc: string; setComposeCc: (cc: string) => void; composeBcc: string; setComposeBcc: (bcc: string) => void; composeSubject: string; setComposeSubject: (subject: string) => void; composeBody: string; setComposeBody: (body: string) => void; showCc: boolean; setShowCc: (show: boolean) => void; showBcc: boolean; setShowBcc: (show: boolean) => void; attachments: any[]; setAttachments: (attachments: any[]) => void; handleSend: () => Promise; originalEmail?: { content: string; type: 'reply' | 'reply-all' | 'forward'; }; onSend: (email: Email) => void; onCancel: () => void; onBodyChange?: (body: string) => void; initialTo?: string; initialSubject?: string; initialBody?: string; initialCc?: string; initialBcc?: string; replyTo?: Email | null; forwardFrom?: Email | null; } export default function ComposeEmail({ showCompose, setShowCompose, composeTo, setComposeTo, composeCc, setComposeCc, composeBcc, setComposeBcc, composeSubject, setComposeSubject, composeBody, setComposeBody, showCc, setShowCc, showBcc, setShowBcc, attachments, setAttachments, handleSend, originalEmail, onSend, onCancel, onBodyChange, initialTo, initialSubject, initialBody, initialCc, initialBcc, replyTo, forwardFrom }: ComposeEmailProps) { const composeBodyRef = useRef(null); const [localContent, setLocalContent] = useState(''); const [isInitialized, setIsInitialized] = useState(false); useEffect(() => { if (composeBodyRef.current && !isInitialized) { let content = ''; if (replyTo || forwardFrom) { // Get the original email content const originalContent = replyTo?.body || forwardFrom?.body || ''; // Generate a unique boundary for MIME parts const boundary = `----=_NextPart_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; // Create MIME headers const mimeHeaders = { 'MIME-Version': '1.0', 'Content-Type': `multipart/alternative; boundary="${boundary}"`, 'From': forwardFrom?.from || replyTo?.from || '', 'Date': new Date(forwardFrom?.date || replyTo?.date || '').toUTCString(), 'Subject': forwardFrom?.subject || replyTo?.subject || '', 'To': forwardFrom?.to || replyTo?.to || '', 'Cc': forwardFrom?.cc || replyTo?.cc || '', }; // Create the reply/forward structure with proper MIME formatting content = `
${forwardFrom ? `
---------- Forwarded message ---------
${Object.entries(mimeHeaders) .filter(([key, value]) => value) .map(([key, value]) => `${key}: ${value}
`) .join('')}
This is a multi-part message in MIME format.

--${boundary}
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable

${originalContent.replace(/\n/g, '
')}

--${boundary}
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable

${originalContent}

--${boundary}--
` : `
On ${new Date(replyTo?.date || '').toLocaleString()}, ${replyTo?.from} wrote:
${originalContent}
`}
`; } else { // For new messages content = `
`; } composeBodyRef.current.innerHTML = content; setIsInitialized(true); // Place cursor at the beginning of the compose area const composeArea = composeBodyRef.current.querySelector('.compose-area'); if (composeArea) { const range = document.createRange(); const sel = window.getSelection(); range.setStart(composeArea, 0); range.collapse(true); sel?.removeAllRanges(); sel?.addRange(range); (composeArea as HTMLElement).focus(); } } }, [composeBody, replyTo, forwardFrom, isInitialized]); // Modified input handler to work with the single contentEditable area const handleInput = (e: React.FormEvent) => { if (!composeBodyRef.current) return; const content = composeBodyRef.current.innerHTML; // Generate a unique boundary for MIME parts const boundary = `----=_NextPart_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; // Create MIME headers const mimeHeaders = { 'MIME-Version': '1.0', 'Content-Type': `multipart/alternative; boundary="${boundary}"`, 'Content-Transfer-Encoding': 'quoted-printable' }; // Create MIME message structure const mimeContent = ` ${Object.entries(mimeHeaders) .map(([key, value]) => `${key}: ${value}`) .join('\n')} This is a multi-part message in MIME format. --${boundary} Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable ${content.replace(/<[^>]*>/g, '')} --${boundary} Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: quoted-printable ${content} --${boundary}-- `; setComposeBody(mimeContent); if (onBodyChange) { onBodyChange(mimeContent); } }; const handleFileAttachment = async (e: React.ChangeEvent) => { if (!e.target.files) return; const newAttachments: any[] = []; const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes const oversizedFiles: string[] = []; for (const file of e.target.files) { if (file.size > MAX_FILE_SIZE) { oversizedFiles.push(file.name); continue; } try { // Read file as base64 const base64Content = await new Promise((resolve) => { const reader = new FileReader(); reader.onloadend = () => { const base64 = reader.result as string; resolve(base64.split(',')[1]); // Remove data URL prefix }; reader.readAsDataURL(file); }); newAttachments.push({ name: file.name, type: file.type, content: base64Content, encoding: 'base64' }); } catch (error) { console.error('Error processing attachment:', error); } } if (oversizedFiles.length > 0) { alert(`The following files exceed the 10MB size limit and were not attached:\n${oversizedFiles.join('\n')}`); } if (newAttachments.length > 0) { setAttachments([...attachments, ...newAttachments]); } }; if (!showCompose) return null; return (
{/* Modal Header */}

{replyTo ? 'Reply' : forwardFrom ? 'Forward' : 'New Message'}

{/* Modal Body */}
{/* To Field */}
setComposeTo(e.target.value)} placeholder="recipient@example.com" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
{/* CC/BCC Toggle Buttons */}
{/* CC Field */} {showCc && (
setComposeCc(e.target.value)} placeholder="cc@example.com" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
)} {/* BCC Field */} {showBcc && (
setComposeBcc(e.target.value)} placeholder="bcc@example.com" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
)} {/* Subject Field */}
setComposeSubject(e.target.value)} placeholder="Enter subject" className="w-full mt-1 bg-white border-gray-300 text-gray-900" />
{/* Message Body - Single contentEditable area with separated regions */}
{/* Modal Footer */}
{/* File Input for Attachments */}
); }