'use client';

import { useState, useRef, useEffect } from 'react';
// Remove direct import of server components
import { 
  X, Paperclip, ChevronDown, ChevronUp, SendHorizontal, Loader2, 
  AlignLeft, AlignRight
} 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 ONLY from the centralized formatter
import { 
  formatForwardedEmail, 
  formatReplyEmail,
  formatEmailForReplyOrForward,
  EmailMessage as FormatterEmailMessage,
  sanitizeHtml
} from '@/lib/utils/email-formatter';

// Define EmailMessage interface locally instead of importing from server-only file
interface EmailAddress {
  name: string;
  address: string;
}

interface EmailMessage {
  id: string;
  messageId?: string;
  subject: string;
  from: EmailAddress[];
  to: EmailAddress[];
  cc?: EmailAddress[];
  bcc?: EmailAddress[];
  date: Date | string;
  flags?: {
    seen: boolean;
    flagged: boolean;
    answered: boolean;
    deleted: boolean;
    draft: boolean;
  };
  preview?: string;
  content?: string;
  html?: string;
  text?: string;
  hasAttachments?: boolean;
  attachments?: any[];
  folder?: string;
  size?: number;
  contentFetched?: boolean;
}

// Legacy interface for backward compatibility with old ComposeEmail component
interface LegacyComposeEmailProps {
  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?: any | null;
  forwardFrom?: any | null;
}

// New interface for the modern ComposeEmail component
interface ComposeEmailProps {
  initialEmail?: EmailMessage | null;
  type?: 'new' | 'reply' | 'reply-all' | 'forward';
  initialRTL?: boolean;
  onClose: () => void;
  onSend: (emailData: {
    to: string;
    cc?: string;
    bcc?: string;
    subject: string;
    body: string;
    attachments?: Array<{
      name: string;
      content: string;
      type: string;
    }>;
  }) => Promise<void>;
}

// Union type to handle both new and legacy props
type ComposeEmailAllProps = ComposeEmailProps | LegacyComposeEmailProps;

// Type guard to check if props are legacy
function isLegacyProps(props: ComposeEmailAllProps): props is LegacyComposeEmailProps {
  return 'showCompose' in props && 'setShowCompose' in props;
}

export default function ComposeEmail(props: ComposeEmailAllProps) {
  // Handle legacy props by adapting them to new component
  if (isLegacyProps(props)) {
    return <LegacyAdapter {...props} />;
  }
  
  // Continue with modern implementation for new props
  const { initialEmail, type = 'new', initialRTL, onClose, onSend } = props;
  
  // Email form state
  const [to, setTo] = useState<string>('');
  const [cc, setCc] = useState<string>('');
  const [bcc, setBcc] = useState<string>('');
  const [subject, setSubject] = useState<string>('');
  const [emailContent, setEmailContent] = useState<string>('');
  const [showCc, setShowCc] = useState<boolean>(false);
  const [showBcc, setShowBcc] = useState<boolean>(false);
  const [sending, setSending] = useState<boolean>(false);
  const [isRTL, setIsRTL] = useState<boolean>(initialRTL || false);
  const [attachments, setAttachments] = useState<Array<{
    name: string;
    content: string;
    type: string;
  }>>([]);
  
  // Refs
  const editorRef = useRef<HTMLDivElement>(null);
  const attachmentInputRef = useRef<HTMLInputElement>(null);
  
  // Initialize RTL state from prop if provided
  useEffect(() => {
    if (initialRTL !== undefined) {
      setIsRTL(initialRTL);
    }
  }, [initialRTL]);
  
  // Initialize the form when replying to or forwarding an email
  useEffect(() => {
    if (initialEmail && type !== 'new') {
      try {
        const formatterEmail: FormatterEmailMessage = {
          id: initialEmail.id,
          messageId: initialEmail.messageId,
          subject: initialEmail.subject,
          from: initialEmail.from || [],
          to: initialEmail.to || [],
          cc: initialEmail.cc || [],
          bcc: initialEmail.bcc || [],
          date: initialEmail.date,
          content: initialEmail.content,
          html: initialEmail.html,
          text: initialEmail.text,
          hasAttachments: initialEmail.hasAttachments || false
        };

        if (type === 'forward') {
          // For forwarding, use the dedicated formatter
          const { subject, content } = formatForwardedEmail(formatterEmail);
          setSubject(subject);
          setEmailContent(content);
        } else {
          // For reply/reply-all, use the reply formatter
          const { to, cc, subject, content } = formatReplyEmail(formatterEmail, type as 'reply' | 'reply-all');
          setTo(to);
          if (cc) {
            setCc(cc);
            setShowCc(true);
          }
          setSubject(subject);
          setEmailContent(content);
        }
        
        // Focus editor after initializing
        setTimeout(() => {
          if (editorRef.current) {
            editorRef.current.focus();
            
            try {
              // Place cursor at the beginning
              const selection = window.getSelection();
              if (selection) {
                const range = document.createRange();
                
                if (editorRef.current.firstChild) {
                  range.setStart(editorRef.current.firstChild, 0);
                  range.collapse(true);
                  
                  selection.removeAllRanges();
                  selection.addRange(range);
                }
              }
            } catch (e) {
              console.error('Error positioning cursor:', e);
            }
          }
        }, 100);
      } catch (error) {
        console.error('Error formatting email:', error);
      }
    }
  }, [initialEmail, type]);

  // Handle attachment selection
  const handleAttachmentClick = () => {
    attachmentInputRef.current?.click();
  };

  // Process selected files
  const handleFileSelection = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

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

  // Handle editor input without re-sanitizing content
  const handleEditorInput = () => {
    if (editorRef.current) {
      // Capture innerHTML directly without reapplying sanitization
      setEmailContent(editorRef.current.innerHTML);
    }
  };

  // Toggle text direction for the entire editor
  const toggleTextDirection = () => {
    // Toggle the RTL state
    const newRTL = !isRTL;
    setIsRTL(newRTL);
    
    // Apply the direction to the editor content immediately
    if (editorRef.current) {
      // Preserve the content but update the direction attributes
      editorRef.current.dir = newRTL ? 'rtl' : 'ltr';
      editorRef.current.style.textAlign = newRTL ? 'right' : 'left';
      editorRef.current.style.direction = newRTL ? 'rtl' : 'ltr';
      
      // No need to modify the content, just let the user edit with proper directionality
    }
  };

  // Send email without modifying pre-formatted content
  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: emailContent, // Use the raw edited content
        attachments
      });
      
      onClose();
    } catch (error) {
      console.error('Error sending email:', error);
      alert('Failed to send email. Please try again.');
    } finally {
      setSending(false);
    }
  };

  return (
    <Card className="w-full max-w-4xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>{type === 'new' ? 'New Message' : type === 'forward' ? 'Forward Email' : 'Reply to Email'}</span>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Recipients, Subject fields */}
        <div className="p-3 border-b space-y-2">
          <div className="flex items-center">
            <span className="w-16 text-sm font-medium">To:</span>
            <Input 
              value={to} 
              onChange={(e) => setTo(e.target.value)} 
              className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
              placeholder="recipient@example.com"
            />
          </div>
          
          {showCc && (
            <div className="flex items-center">
              <span className="w-16 text-sm font-medium">Cc:</span>
              <Input 
                value={cc} 
                onChange={(e) => setCc(e.target.value)} 
                className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
                placeholder="cc@example.com"
              />
            </div>
          )}
          
          {showBcc && (
            <div className="flex items-center">
              <span className="w-16 text-sm font-medium">Bcc:</span>
              <Input 
                value={bcc} 
                onChange={(e) => setBcc(e.target.value)} 
                className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
                placeholder="bcc@example.com"
              />
            </div>
          )}
          
          {/* CC/BCC controls */}
          <div className="flex items-center text-xs">
            <button 
              className="text-primary hover:underline mr-3 flex items-center"
              onClick={() => setShowCc(!showCc)}
            >
              {showCc ? (
                <>
                  <ChevronUp className="h-3 w-3 mr-0.5" />
                  Hide Cc
                </>
              ) : (
                <>
                  <ChevronDown className="h-3 w-3 mr-0.5" />
                  Show Cc
                </>
              )}
            </button>
            
            <button 
              className="text-primary hover:underline flex items-center"
              onClick={() => setShowBcc(!showBcc)}
            >
              {showBcc ? (
                <>
                  <ChevronUp className="h-3 w-3 mr-0.5" />
                  Hide Bcc
                </>
              ) : (
                <>
                  <ChevronDown className="h-3 w-3 mr-0.5" />
                  Show Bcc
                </>
              )}
            </button>
          </div>
          
          <div className="flex items-center">
            <span className="w-16 text-sm font-medium">Subject:</span>
            <Input 
              value={subject} 
              onChange={(e) => setSubject(e.target.value)} 
              className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
              placeholder="Subject"
            />
          </div>
        </div>
        
        {/* Email Body Editor */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <label htmlFor="body" className="text-sm font-medium">Message</label>
            <Button 
              variant="outline" 
              size="sm" 
              onClick={toggleTextDirection} 
              className="h-8 px-3 text-xs"
            >
              {isRTL ? 
                <><AlignLeft className="h-4 w-4 mr-1" /> Switch to LTR</> : 
                <><AlignRight className="h-4 w-4 mr-1" /> Switch to RTL</>
              }
            </Button>
          </div>
          
          {/* Email editor with a single editable area */}
          <div className="border rounded-md overflow-hidden">
            <div
              ref={editorRef}
              contentEditable={!sending}
              className="w-full p-4 min-h-[300px] focus:outline-none"
              onInput={handleEditorInput}
              // Use dangerouslySetInnerHTML without sanitizing again to preserve our formatting
              dangerouslySetInnerHTML={{ __html: emailContent }}
              dir={isRTL ? 'rtl' : 'ltr'}
              style={{ 
                textAlign: isRTL ? 'right' : 'left',
                direction: isRTL ? 'rtl' : 'ltr',
                unicodeBidi: 'isolate'
              }}
            />
          </div>
        </div>
        
        {/* Attachments section */}
        {attachments.length > 0 && (
          <div className="border-t p-2">
            <div className="text-sm font-medium mb-1">Attachments:</div>
            <div className="flex flex-wrap gap-2">
              {attachments.map((attachment, index) => (
                <div key={index} className="flex items-center gap-1 text-sm bg-muted px-2 py-1 rounded">
                  <Paperclip className="h-3 w-3" />
                  <span>{attachment.name}</span>
                  <button 
                    onClick={() => removeAttachment(index)}
                    className="ml-1 text-muted-foreground hover:text-destructive"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}
      </CardContent>
      
      <CardFooter className="border-t p-3 flex justify-between">
        <div>
          <input
            type="file"
            ref={attachmentInputRef}
            className="hidden"
            onChange={handleFileSelection}
            multiple
          />
          <Button
            variant="outline"
            size="sm"
            onClick={handleAttachmentClick}
          >
            <Paperclip className="h-4 w-4 mr-1" />
            Attach
          </Button>
        </div>
        
        <Button 
          size="sm" 
          onClick={handleSend}
          disabled={sending}
        >
          {sending ? (
            <>
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              Sending...
            </>
          ) : (
            <>
              <SendHorizontal className="h-4 w-4 mr-1" />
              Send
            </>
          )}
        </Button>
      </CardFooter>
    </Card>
  );
}

// Adapter component for legacy props
function LegacyAdapter({
  showCompose,
  setShowCompose,
  composeTo,
  setComposeTo,
  composeCc,
  setComposeCc,
  composeBcc,
  setComposeBcc,
  composeSubject,
  setComposeSubject,
  composeBody,
  setComposeBody,
  showCc,
  setShowCc,
  showBcc,
  setShowBcc,
  attachments,
  setAttachments,
  handleSend,
  originalEmail,
  onSend,
  onCancel,
  replyTo,
  forwardFrom
}: LegacyComposeEmailProps) {
  // Check if the user has RTL preference
  const [preferRTL, setPreferRTL] = useState<boolean>(false);
  
  // Detect RTL content in body on initialization
  useEffect(() => {
    if (!composeBody) return;
    
    // Better RTL detection based on common RTL languages (Arabic, Hebrew, Persian, Urdu, etc.)
    const rtlRegex = /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/;
    
    // If there are RTL characters, set preferRTL to true
    if (rtlRegex.test(composeBody)) {
      setPreferRTL(true);
      console.log('RTL text detected - setting editor to RTL mode');
    }
  }, [composeBody]);
  
  // Determine the type from the original email or subject
  const determineType = (): 'new' | 'reply' | 'reply-all' | 'forward' => {
    if (originalEmail) {
      return originalEmail.type;
    }
    
    if (composeSubject.startsWith('Re:')) {
      return 'reply';
    }
    
    if (composeSubject.startsWith('Fwd:')) {
      return 'forward';
    }
    
    return 'new';
  };
  
  // Convert legacy attachments format to new format
  const convertAttachments = () => {
    return (attachments || []).map((att: any) => ({
      name: att.name || 'attachment',
      content: typeof att.content === 'string' ? att.content : '',
      type: att.type || 'application/octet-stream'
    }));
  };
  
  // Create an EmailMessage compatible object from composeBody
  // This is crucial for displaying original content in replies/forwards
  const createEmailMessageFromContent = (): EmailMessage | null => {
    const type = determineType();
    
    // Only create an email object if we're replying or forwarding
    if (type === 'new' || !composeBody) {
      return null;
    }
    
    // For forwarded content, we need to preserve all the original formatting
    // The composeBody already contains the formatted message with headers
    return {
      id: 'temp-id',
      messageId: '',
      subject: composeSubject,
      from: [{ name: '', address: '' }],
      to: [{ name: '', address: '' }],
      date: new Date(),
      // Always use the full composeBody to ensure nested forwards are preserved
      content: composeBody,
      html: composeBody,
      hasAttachments: false
    };
  };
  
  // If not showing compose, return null
  if (!showCompose) {
    return null;
  }
  
  // Create email message from content if available
  const emailForCompose = createEmailMessageFromContent();
  const type = determineType();
  
  return (
    <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 max-h-[90vh] bg-white rounded-xl shadow-xl overflow-auto mx-4">
        <ComposeEmail
          initialEmail={emailForCompose}
          type={type}
          initialRTL={preferRTL}
          onClose={() => {
            onCancel?.();
            setShowCompose(false);
          }}
          onSend={async (emailData: {
            to: string;
            cc?: string;
            bcc?: string;
            subject: string;
            body: string;
            attachments?: Array<{
              name: string;
              content: string;
              type: string;
            }>;
          }) => {
            // Update legacy state before sending
            setComposeTo(emailData.to);
            if (emailData.cc) setComposeCc(emailData.cc);
            if (emailData.bcc) setComposeBcc(emailData.bcc);
            setComposeSubject(emailData.subject);
            setComposeBody(emailData.body);
            
            // Call the legacy onSend function
            await onSend(emailData);
          }}
        />
      </div>
    </div>
  );
} 