'use client';

import React, { useEffect, useState, useRef } 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 { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import DOMPurify from 'isomorphic-dompurify';
import { formatEmailForReply, formatEmailForForward, EmailMessageForFormatting } from '@/lib/email-formatter';
import { getEmailContent, getUserEmailCredentials } from '@/lib/services/email-service';

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 [isSending, setIsSending] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const contentEditableRef = useRef<HTMLDivElement>(null);
  const [useRichEditor, setUseRichEditor] = useState(false);
  const [userMessage, setUserMessage] = useState('');
  const [quotedContent, setQuotedContent] = useState('');

  useEffect(() => {
    // When forwarding or replying, use rich editor
    setUseRichEditor(!!replyTo || !!forwardFrom);
  }, [replyTo, forwardFrom]);

  useEffect(() => {
    // Initialize reply if replyTo is provided
    if (replyTo) {
      initializeReplyEmail(replyTo);
    }
  }, [replyTo, setComposeTo, setComposeSubject, setComposeBody]);
  
  useEffect(() => {
    // Initialize forward email if forwardFrom is provided
    if (forwardFrom) {
      initializeForwardedEmail(forwardFrom);
    }
  }, [forwardFrom]);

  // Initialize forwarded email content
  const initializeForwardedEmail = async (email: any) => {
    console.log("Initializing forwarded email", email);
    try {
      // Convert the email to the format expected by our formatter
      const emailForFormatting: EmailMessageForFormatting = {
        subject: email.subject,
        from: email.from,
        to: email.to,
        date: email.date,
        html: email.html || email.content,
        text: email.text,
        cc: email.cc,
        bcc: email.bcc
      };

      // Use the client-side formatter
      const formattedEmail = formatEmailForForward(emailForFormatting);
      
      setComposeSubject(formattedEmail.subject);
      setQuotedContent(formattedEmail.body);
      setComposeBody(''); // Clear user message when forwarding
    } catch (error) {
      console.error("Error initializing forwarded email:", error);
      setQuotedContent(`
        <div style="padding: 10px; text-align: center; background-color: #f8f8f8; border: 1px dashed #ccc; margin: 10px 0;">
          Error loading original message content
        </div>
      `);
    }
  };

  // Initialize reply email content
  const initializeReplyEmail = async (email: any, replyType: 'reply' | 'replyAll' = 'reply') => {
    console.log("Initializing reply email", email, replyType);
    try {
      // Convert the email to the format expected by our formatter
      const emailForFormatting: EmailMessageForFormatting = {
        subject: email.subject,
        from: email.from,
        to: email.to,
        date: email.date,
        html: email.html || email.content,
        text: email.text,
        cc: email.cc,
        bcc: email.bcc
      };

      // Use the client-side formatter
      const formattedEmail = formatEmailForReply(emailForFormatting, replyType);
      
      setComposeSubject(formattedEmail.subject);
      
      // Set recipients
      if (formattedEmail.to) {
        const toAddresses = formattedEmail.to.map(recipient => 
          recipient.name ? `${recipient.name} <${recipient.address}>` : recipient.address
        ).join(', ');
        setComposeTo(toAddresses);
      }
      
      if (formattedEmail.cc && formattedEmail.cc.length > 0) {
        const ccAddresses = formattedEmail.cc.map(recipient => 
          recipient.name ? `${recipient.name} <${recipient.address}>` : recipient.address
        ).join(', ');
        setComposeCc(ccAddresses);
        setShowCc(true);
      }
      
      setQuotedContent(formattedEmail.body);
      setComposeBody(''); // Clear user message when replying
    } catch (error) {
      console.error("Error initializing reply email:", error);
      setQuotedContent(`
        <div style="padding: 10px; text-align: center; background-color: #f8f8f8; border: 1px dashed #ccc; margin: 10px 0;">
          Error loading original message content
        </div>
      `);
    }
  };

  // Handle file attachment selection
  const handleFileAttachment = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const newFiles = Array.from(e.target.files);
      setAttachments([...attachments, ...newFiles]);
    }
  };

  // Handle contentEditable input changes
  const handleUserMessageChange = () => {
    if (contentEditableRef.current) {
      setUserMessage(contentEditableRef.current.innerHTML);
      
      // Combine user message with quoted content for the full email body
      const combined = `${contentEditableRef.current.innerHTML}${quotedContent ? quotedContent : ''}`;
      setComposeBody(combined);
    }
  };

  // Handle sending email with combined content
  const handleSendWithCombinedContent = async () => {
    if (isSending) return;
    
    try {
      setIsSending(true);
      
      // For rich editor, combine user message with quoted content
      if (useRichEditor) {
        const combinedContent = `${userMessage || ''}${quotedContent ? quotedContent : ''}`;
        setComposeBody(combinedContent);
        
        // Wait for state update to complete
        await new Promise(resolve => setTimeout(resolve, 0));
      }
      
      // Call the provided onSend function
      await onSend({
        to: composeTo,
        cc: composeCc,
        bcc: composeBcc,
        subject: composeSubject,
        body: composeBody,
        attachments: attachments
      });
      
      // Reset the compose state
      setShowCompose(false);
      setComposeTo('');
      setComposeCc('');
      setComposeBcc('');
      setComposeSubject('');
      setComposeBody('');
      setShowCc(false);
      setShowBcc(false);
      setAttachments([]);
      setUserMessage('');
      setQuotedContent('');
      
    } catch (error) {
      console.error('Failed to send email:', error);
    } finally {
      setIsSending(false);
    }
  };

  return (
    <>
      {/* Compose Email Modal */}
      {showCompose && (
        <div className="fixed inset-0 bg-gray-600/30 backdrop-blur-sm z-50 flex items-center justify-center">
          <div className="w-full max-w-2xl h-[80vh] bg-white rounded-xl shadow-xl flex flex-col mx-4">
            {/* Modal Header */}
            <div className="flex items-center justify-between px-6 py-3 border-b border-gray-200">
              <h3 className="text-lg font-semibold text-gray-900">
                {composeSubject.startsWith('Re:') ? 'Reply' : 
                 composeSubject.startsWith('Fwd:') ? 'Forward' : 'New Message'}
              </h3>
              <Button
                variant="ghost"
                size="icon"
                className="hover:bg-gray-100 rounded-full"
                onClick={() => {
                  setShowCompose(false);
                  setComposeTo('');
                  setComposeCc('');
                  setComposeBcc('');
                  setComposeSubject('');
                  setComposeBody('');
                  setShowCc(false);
                  setShowBcc(false);
                }}
              >
                <X className="h-5 w-5 text-gray-500" />
              </Button>
            </div>

            {/* Modal Body */}
            <div className="flex-1 overflow-y-auto">
              <div className="p-6 space-y-4">
                {/* To Field */}
                <div>
                  <Label htmlFor="to" className="block text-sm font-medium text-gray-700">To</Label>
                  <Input
                    id="to"
                    value={composeTo}
                    onChange={(e) => setComposeTo(e.target.value)}
                    placeholder="recipient@example.com"
                    className="w-full mt-1 bg-white border-gray-300 text-gray-900"
                  />
                </div>

                {/* CC/BCC Toggle Buttons */}
                <div className="flex items-center gap-4">
                  <button
                    type="button"
                    className="text-blue-600 hover:text-blue-700 text-sm font-medium"
                    onClick={() => setShowCc(!showCc)}
                  >
                    {showCc ? 'Hide Cc' : 'Add Cc'}
                  </button>
                  <button
                    type="button"
                    className="text-blue-600 hover:text-blue-700 text-sm font-medium"
                    onClick={() => setShowBcc(!showBcc)}
                  >
                    {showBcc ? 'Hide Bcc' : 'Add Bcc'}
                  </button>
                </div>

                {/* CC Field */}
                {showCc && (
                  <div>
                    <Label htmlFor="cc" className="block text-sm font-medium text-gray-700">Cc</Label>
                    <Input
                      id="cc"
                      value={composeCc}
                      onChange={(e) => setComposeCc(e.target.value)}
                      placeholder="cc@example.com"
                      className="w-full mt-1 bg-white border-gray-300 text-gray-900"
                    />
                  </div>
                )}

                {/* BCC Field */}
                {showBcc && (
                  <div>
                    <Label htmlFor="bcc" className="block text-sm font-medium text-gray-700">Bcc</Label>
                    <Input
                      id="bcc"
                      value={composeBcc}
                      onChange={(e) => setComposeBcc(e.target.value)}
                      placeholder="bcc@example.com"
                      className="w-full mt-1 bg-white border-gray-300 text-gray-900"
                    />
                  </div>
                )}

                {/* Subject Field */}
                <div>
                  <Label htmlFor="subject" className="block text-sm font-medium text-gray-700">Subject</Label>
                  <Input
                    id="subject"
                    value={composeSubject}
                    onChange={(e) => setComposeSubject(e.target.value)}
                    placeholder="Enter subject"
                    className="w-full mt-1 bg-white border-gray-300 text-gray-900"
                  />
                </div>

                {/* Message Body - conditionally render either rich editor or textarea */}
                <div>
                  <Label htmlFor="message" className="block text-sm font-medium text-gray-700">Message</Label>
                  
                  {useRichEditor ? (
                    <div className="mt-1 border border-gray-300 rounded-md overflow-hidden">
                      {/* User input area - completely separate from quoted content */}
                      <div
                        ref={contentEditableRef}
                        contentEditable="true"
                        className="w-full p-3 bg-white min-h-[100px] text-gray-900 email-editor"
                        onInput={handleUserMessageChange}
                        dangerouslySetInnerHTML={userMessage ? { __html: userMessage } : { __html: '<p>Write your message here...</p>' }}
                      />
                      
                      {/* Original email content - also editable */}
                      {quotedContent && (
                        <div 
                          className="w-full bg-gray-50 border-t border-gray-300 email-content-wrapper"
                        >
                          <div 
                            className="p-3 opacity-90 text-sm email-content"
                            contentEditable="true"
                            dangerouslySetInnerHTML={{ __html: quotedContent }}
                            onInput={(e) => {
                              const target = e.currentTarget;
                              setQuotedContent(target.innerHTML);
                            }}
                          />
                        </div>
                      )}
                    </div>
                  ) : (
                    <Textarea
                      id="message"
                      value={composeBody}
                      onChange={(e) => setComposeBody(e.target.value)}
                      placeholder="Write your message..."
                      className="w-full mt-1 min-h-[200px] bg-white border-gray-300 text-gray-900 resize-none email-editor"
                    />
                  )}
                </div>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="flex items-center justify-between px-6 py-3 border-t border-gray-200 bg-white">
              <div className="flex items-center gap-2">
                {/* File Input for Attachments */}
                <input
                  type="file"
                  id="file-attachment"
                  className="hidden"
                  multiple
                  onChange={handleFileAttachment}
                />
                <label htmlFor="file-attachment">
                  <Button 
                    variant="outline" 
                    size="icon"
                    className="rounded-full bg-white hover:bg-gray-100 border-gray-300"
                    onClick={(e) => {
                      e.preventDefault();
                      document.getElementById('file-attachment')?.click();
                    }}
                  >
                    <Paperclip className="h-4 w-4 text-gray-600" />
                  </Button>
                </label>
              </div>
              <div className="flex items-center gap-3">
                <Button 
                  variant="ghost"
                  className="text-gray-600 hover:text-gray-700 hover:bg-gray-100"
                  onClick={() => setShowCompose(false)}
                >
                  Cancel
                </Button>
                <Button
                  className="bg-blue-600 text-white hover:bg-blue-700"
                  onClick={handleSendWithCombinedContent}
                  disabled={isSending}
                >
                  {isSending ? 'Sending...' : 'Send'}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
} 