'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'; 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') { const formattedEmail = formatEmailForReplyOrForward(initialEmail, type as 'reply' | 'reply-all' | 'forward'); 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]); // 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}
))}
)}
); }