Neah/components/ComposeEmail.tsx
2025-04-26 11:41:20 +02:00

314 lines
10 KiB
TypeScript

'use client';
import { useState, useRef, useEffect } from 'react';
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 DOMPurify from 'isomorphic-dompurify';
import { formatEmailForReplyOrForward } from '@/lib/services/email-service';
import { Email } from '@/app/courrier/page';
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<void>;
originalEmail?: {
content: string;
type: 'reply' | 'reply-all' | 'forward';
};
onSend: (email: any) => Promise<void>;
onCancel: () => void;
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,
replyTo,
forwardFrom,
onSend,
onCancel
}: ComposeEmailProps) {
const [sending, setSending] = useState(false);
const editorRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (editorRef.current) {
editorRef.current.focus();
}
}, [showCompose]);
// Initialize content when replying or forwarding
useEffect(() => {
// Handle reply or forward initialization
if (replyTo) {
// For reply/reply-all
const formattedEmail = formatEmailForReplyOrForward(replyTo as any, 'reply');
setComposeTo(formattedEmail.to);
setComposeSubject(formattedEmail.subject);
setComposeBody(formattedEmail.body);
// Show CC if needed for reply-all
if (formattedEmail.cc) {
setComposeCc(formattedEmail.cc);
setShowCc(true);
}
} else if (forwardFrom) {
// For forward
initializeForwardedEmail(forwardFrom);
}
}, [replyTo, forwardFrom]);
// Initialize forwarded email content
const initializeForwardedEmail = async (email: any) => {
if (!email) return;
// Format subject with Fwd: prefix if needed
const subjectBase = email.subject || '(No subject)';
const subjectRegex = /^(Fwd|FW|Forward):\s*/i;
const subject = subjectRegex.test(subjectBase)
? subjectBase
: `Fwd: ${subjectBase}`;
setComposeSubject(subject);
// Create header for forwarded email
const headerHtml = `
<div style="border-top: 1px solid #e1e1e1; margin-top: 20px; padding-top: 15px; font-family: Arial, sans-serif;">
<div style="margin-bottom: 15px;">
<div style="font-weight: normal; margin-bottom: 10px;">---------- Forwarded message ---------</div>
<div><b>From:</b> ${email.fromName || email.from}</div>
<div><b>Date:</b> ${new Date(email.date).toLocaleString()}</div>
<div><b>Subject:</b> ${email.subject || '(No subject)'}</div>
<div><b>To:</b> ${email.to}</div>
</div>
</div>
`;
// Prepare content
let contentHtml = '<div style="color: #666; font-style: italic; padding: 15px; border: 1px dashed #ccc; margin: 10px 0; text-align: center; background-color: #f9f9f9;">No content available</div>';
if (email.content) {
// Sanitize the content
contentHtml = DOMPurify.sanitize(email.content, {
ADD_TAGS: ['style'],
FORBID_TAGS: ['script', 'iframe']
});
}
// Set body with header and content
setComposeBody(`
${headerHtml}
<div style="margin-top: 10px;">
${contentHtml}
</div>
`);
};
if (!showCompose) return null;
const handleFileSelection = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const newAttachments = Array.from(e.target.files).map(file => ({
name: file.name,
type: file.type,
size: file.size,
file
}));
setAttachments([...attachments, ...newAttachments]);
}
};
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
<Card className="w-full max-w-3xl">
<CardHeader className="flex flex-row items-center border-b p-4">
<CardTitle className="text-lg">
{replyTo ? 'Reply' : forwardFrom ? 'Forward' : 'New Message'}
</CardTitle>
<Button
variant="ghost"
size="icon"
className="ml-auto"
onClick={onCancel}
>
<X className="h-4 w-4" />
</Button>
</CardHeader>
<CardContent className="p-4 space-y-4">
<div className="space-y-2">
<div className="flex items-center border-b py-2">
<span className="w-16 text-sm text-gray-500">To:</span>
<Input
value={composeTo}
onChange={(e) => setComposeTo(e.target.value)}
className="border-0 focus-visible:ring-0"
placeholder="recipient@example.com"
/>
</div>
{showCc && (
<div className="flex items-center border-b py-2">
<span className="w-16 text-sm text-gray-500">Cc:</span>
<Input
value={composeCc}
onChange={(e) => setComposeCc(e.target.value)}
className="border-0 focus-visible:ring-0"
placeholder="cc@example.com"
/>
</div>
)}
{showBcc && (
<div className="flex items-center border-b py-2">
<span className="w-16 text-sm text-gray-500">Bcc:</span>
<Input
value={composeBcc}
onChange={(e) => setComposeBcc(e.target.value)}
className="border-0 focus-visible:ring-0"
placeholder="bcc@example.com"
/>
</div>
)}
<div className="flex items-center border-b py-2">
<span className="w-16 text-sm text-gray-500">Subject:</span>
<Input
value={composeSubject}
onChange={(e) => setComposeSubject(e.target.value)}
className="border-0 focus-visible:ring-0"
placeholder="Subject"
/>
</div>
<div className="flex items-center text-xs text-blue-600 space-x-2 py-1">
{!showCc && (
<button onClick={() => setShowCc(true)} className="hover:underline">
Add Cc
</button>
)}
{!showBcc && (
<button onClick={() => setShowBcc(true)} className="hover:underline">
Add Bcc
</button>
)}
</div>
</div>
<div
ref={editorRef}
className="min-h-[300px] p-2 focus:outline-none overflow-auto"
contentEditable
dangerouslySetInnerHTML={{ __html: composeBody }}
onInput={(e) => setComposeBody(e.currentTarget.innerHTML)}
/>
{attachments.length > 0 && (
<div className="border-t pt-3">
<h4 className="text-sm font-medium mb-2">Attachments</h4>
<div className="flex flex-wrap gap-2">
{attachments.map((attachment, index) => (
<div key={index} className="flex items-center bg-gray-100 rounded px-2 py-1">
<span className="text-sm truncate max-w-[150px]">{attachment.name}</span>
<button
className="ml-1 text-gray-500 hover:text-gray-700"
onClick={() => {
const newAttachments = [...attachments];
newAttachments.splice(index, 1);
setAttachments(newAttachments);
}}
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
</div>
)}
</CardContent>
<CardFooter className="border-t p-4 flex justify-between">
<div className="flex items-center space-x-2">
<input
type="file"
ref={fileInputRef}
className="hidden"
onChange={handleFileSelection}
multiple
/>
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Paperclip className="h-4 w-4 mr-1" />
Attach
</Button>
</div>
<Button
onClick={async () => {
setSending(true);
try {
await handleSend();
onCancel();
} catch (error) {
console.error('Error sending email:', error);
} finally {
setSending(false);
}
}}
disabled={sending || !composeTo.trim()}
>
{sending ? (
<>
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
Sending...
</>
) : (
<>
<SendHorizontal className="h-4 w-4 mr-1" />
Send
</>
)}
</Button>
</CardFooter>
</Card>
</div>
);
}