'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 { formatEmailForReply, formatEmailForForward } from '@/lib/email-formatter';

interface EmailObject {
  id?: string;
  from?: string;
  fromName?: string;
  to?: string;
  subject?: string;
  content?: string;
  html?: string;
  text?: string;
  body?: string;
  date?: string;
  read?: boolean;
  starred?: boolean;
  attachments?: { name: string; url: string }[];
  folder?: string;
  cc?: string;
  bcc?: string;
}

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?: EmailObject | null;
  forwardFrom?: EmailObject | 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(() => {
    // Initialize reply if replyTo is provided
    if (replyTo) {
      // For reply/reply-all
      const formattedEmail = formatEmailForReply(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) {
      // Initialize forward email if forwardFrom is provided
      initializeForwardedEmail(forwardFrom);
    }
  }, [replyTo, forwardFrom]);

  // Initialize forwarded email content
  const initializeForwardedEmail = async (email: any) => {
    console.log('Initializing forwarded email:', email);

    // Use our client-side formatter
    const formattedEmail = formatEmailForForward(email);
    
    // Set the formatted subject with Fwd: prefix
    setComposeSubject(formattedEmail.subject);
    
    // Get the email content and create a forward with proper formatting
    let finalContent = '';
    
    // Add the email header with proper styling
    finalContent += formattedEmail.headerHtml;
    
    // Add the original content
    if (email.content) {
      finalContent += email.content;
    } else if (email.html) {
      finalContent += email.html;
    } else if (email.text) {
      finalContent += `<pre>${email.text}</pre>`;
    } else if (email.body) {
      finalContent += email.body;
    } else {
      finalContent += `<div style="border: 1px dashed #ccc; padding: 10px; margin: 10px 0; text-align: center; background-color: #f9f9f9;">
        No content available
      </div>`;
    }
    
    setComposeBody(finalContent);
  };

  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>
  );
} 