'use client';

import { useRef, useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Paperclip, X } from 'lucide-react';
import { Textarea } from '@/components/ui/textarea';
import { decodeComposeContent, encodeComposeContent } from '@/lib/compose-mime-decoder';
import { Email } from '@/app/courrier/page';
import mime from 'mime';
import { simpleParser } from 'mailparser';

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: Email) => void;
  onCancel: () => void;
  onBodyChange?: (body: string) => void;
  initialTo?: string;
  initialSubject?: string;
  initialBody?: string;
  initialCc?: string;
  initialBcc?: string;
  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,
  onSend,
  onCancel,
  onBodyChange,
  initialTo,
  initialSubject,
  initialBody,
  initialCc,
  initialBcc,
  replyTo,
  forwardFrom
}: ComposeEmailProps) {
  const composeBodyRef = useRef<HTMLDivElement>(null);
  const [localContent, setLocalContent] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  
  useEffect(() => {
    if (replyTo || forwardFrom) {
      const initializeContent = async () => {
        if (!composeBodyRef.current) return;
        
        try {
          const emailToProcess = replyTo || forwardFrom;
          console.log('[DEBUG] Initializing compose content with email:', 
            emailToProcess ? {
              id: emailToProcess.id,
              subject: emailToProcess.subject,
              hasContent: !!emailToProcess.content,
              contentLength: emailToProcess.content ? emailToProcess.content.length : 0,
              preview: emailToProcess.preview
            } : 'null'
          );
          
          // Set initial loading state
          composeBodyRef.current.innerHTML = `
            <div class="compose-area" contenteditable="true">
              <br/>
              <div class="text-gray-500">Loading original message...</div>
            </div>
          `;
          
          setIsLoading(true);

          // Check if we have content
          if (!emailToProcess?.content) {
            console.error('[DEBUG] No email content found to process');
            
            // Try to use body property if content is not available (for backward compatibility)
            if (emailToProcess && 'body' in emailToProcess && emailToProcess.body) {
              console.log('[DEBUG] Using body property as fallback for content');
              emailToProcess.content = emailToProcess.body;
            } else if (emailToProcess) {
              console.log('[DEBUG] Attempting to fetch email content directly');
              try {
                // Fetch the email content if not available
                const response = await fetch(`/api/courrier/${emailToProcess.id}?folder=${encodeURIComponent(emailToProcess.folder || 'INBOX')}&fetchFull=true`);
                
                if (!response.ok) {
                  throw new Error(`Failed to fetch email content: ${response.status}`);
                }
                
                const fullContent = await response.json();
                console.log('[DEBUG] API response for full email content:', {
                  hasContent: !!fullContent?.content,
                  hasBody: !!fullContent?.body,
                  hasHtml: !!fullContent?.html,
                  hasText: !!fullContent?.text,
                  contentLength: fullContent?.content?.length || 0
                });
                
                // Update the email content with the fetched full content
                if (fullContent && fullContent.content) {
                  console.log('[DEBUG] Successfully fetched content for reply/forward');
                  emailToProcess.content = fullContent.content;
                } else if (fullContent && fullContent.body) {
                  console.log('[DEBUG] Successfully fetched body for reply/forward');
                  emailToProcess.content = fullContent.body;
                } else if (fullContent && fullContent.html) {
                  console.log('[DEBUG] Successfully fetched HTML for reply/forward');
                  emailToProcess.content = fullContent.html;
                } else if (fullContent && fullContent.text) {
                  console.log('[DEBUG] Successfully fetched TEXT for reply/forward');
                  emailToProcess.content = fullContent.text;
                } else {
                  console.error('[DEBUG] No usable content found in API response');
                  
                  // Try using fullContent directly if it's a string
                  if (typeof fullContent === 'string' && fullContent.length > 0) {
                    console.log('[DEBUG] Using fullContent string directly');
                    emailToProcess.content = fullContent;
                  } else {
                    throw new Error('No content in fetched email');
                  }
                }
                
                // Ensure we actually have content
                if (!emailToProcess.content || emailToProcess.content.trim().length === 0) {
                  console.error('[DEBUG] Content still empty after fetch, using fallback');
                  // Use any available preview or raw data
                  emailToProcess.content = emailToProcess.preview || 
                                          (fullContent.raw ? fullContent.raw : 'Email content unavailable');
                }
              } catch (fetchError) {
                console.error('[DEBUG] Error fetching email content:', fetchError);
                composeBodyRef.current.innerHTML = `
                  <div class="compose-area" contenteditable="true">
                    <br/>
                    <div style="color: #ef4444;">Error: No original message content available.</div>
                    <div style="color: #64748b; font-size: 0.875rem; margin-top: 0.5rem;">
                      Please select the email again or try refreshing the page.
                    </div>
                  </div>
                `;
                setIsLoading(false);
                return;
              }
            } else {
              // No emailToProcess available
              composeBodyRef.current.innerHTML = `
                <div class="compose-area" contenteditable="true">
                  <br/>
                  <div style="color: #ef4444;">Error: No email selected for reply/forward.</div>
                </div>
              `;
              setIsLoading(false);
              return;
            }
          }

          // Add more debug logging to track content fetching
          console.log('[DEBUG] Sending content to parse-email API, content type:', 
            typeof emailToProcess!.content, 
            'length:', emailToProcess!.content.length,
            'starts with:', emailToProcess!.content.substring(0, 50)
          );
          
          let emailContent;
          let parseSuccess = false;
          
          try {
            // Parse the original email using the API
            const response = await fetch('/api/parse-email', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ email: emailToProcess.content }),
            });

            console.log('[DEBUG] Parse-email API response status:', response.status);
            
            const data = await response.json();
            console.log('[DEBUG] Parse-email API response:', {
              hasHtml: !!data.html,
              hasText: !!data.text,
              subject: data.subject,
              error: data.error
            });
            
            if (!response.ok) {
              throw new Error(data.error || 'Failed to parse email');
            }

            // Prioritize HTML content if available, fallback to text
            emailContent = data.html || data.text || '';
            
            // Add a fallback check if both HTML and text are empty
            if (!emailContent.trim()) {
              // Try to extract content from the raw source
              console.log('[DEBUG] Empty content from parser, using raw content as fallback');
              emailContent = emailToProcess.content;
              
              // If content looks like HTML, use it directly, otherwise wrap in pre tags
              if (!emailContent.startsWith('<') || !emailContent.endsWith('>')) {
                emailContent = `<pre style="white-space: pre-wrap; word-break: break-word;">${emailContent}</pre>`;
              }
            }
            
            parseSuccess = true;
          } catch (error) {
            console.error('[DEBUG] API parse error:', error);
            // Try to use the content directly if API fails
            emailContent = emailToProcess.content;
            
            // If content looks like HTML, use it directly, otherwise wrap in pre tags
            if (!emailContent.startsWith('<') || !emailContent.endsWith('>')) {
              emailContent = `<pre style="white-space: pre-wrap; word-break: break-word;">${emailContent}</pre>`;
            }
          }
          
          if (!emailContent || !emailContent.trim()) {
            console.warn('[DEBUG] No content available after parsing, trying direct content');
            // Final fallback: Try to use direct content or preview
            emailContent = emailToProcess.content || emailToProcess.preview || 
                          (emailToProcess.body ? 
                            `<pre style="white-space: pre-wrap; word-break: break-word;">${emailToProcess.body}</pre>` : 
                            '<div>No content available in the original message</div>');
          }
          
          // Format the reply/forward content
          const formatQuotedContent = (content: string) => {
            // First try to clean up any problematic formatting
            let cleanedContent = content;
            
            // If content is very short or empty, add a clear message
            if (!cleanedContent || cleanedContent.trim().length < 10) {
              return `<div style="color: #888; font-style: italic;">Original message was empty or could not be loaded</div>`;
            }
            
            // If we're working with plain text, make it readable
            if (!cleanedContent.includes('<') || !cleanedContent.includes('>')) {
              return `<pre style="white-space: pre-wrap; word-break: break-word; font-family: ui-sans-serif, system-ui, sans-serif; margin: 0;">${cleanedContent}</pre>`;
            }
            
            // For HTML content, ensure it's properly contained
            return cleanedContent;
          };

          // Process email content
          const formatEmailAddresses = (addresses: any) => {
            if (!addresses) return 'Unknown';
            if (typeof addresses === 'string') return addresses;
            if (Array.isArray(addresses)) {
              return addresses.map(addr => addr.name || addr.address).join(', ');
            }
            return String(addresses);
          };

          const quotedContent = forwardFrom ? `
            <div class="forwarded-message" style="border-top: 1px solid #e5e7eb; padding-top: 20px; margin-top: 20px; color: #6b7280; font-size: 0.875rem;">
              ---------- Forwarded message ---------<br/>
              From: ${formatEmailAddresses(emailToProcess?.from) || 'Unknown Sender'}<br/>
              Date: ${new Date(emailToProcess?.date || Date.now()).toLocaleString()}<br/>
              Subject: ${emailToProcess?.subject || 'No Subject'}<br/>
              To: ${formatEmailAddresses(emailToProcess?.to) || ''}<br/>
              ${emailToProcess?.cc ? `Cc: ${formatEmailAddresses(emailToProcess.cc)}<br/>` : ''}
            </div>
            <div class="message-content" style="margin-top: 10px; border: 1px solid #e5e7eb; padding: 10px; border-radius: 4px; max-height: 300px; overflow-y: auto; color: #374151;">
              ${formatQuotedContent(emailContent)}
            </div>
          ` : `
            <div class="quoted-message" style="border-top: 1px solid #e5e7eb; padding-top: 20px; margin-top: 20px; color: #6b7280; font-size: 0.875rem;">
              On ${new Date(emailToProcess?.date || Date.now()).toLocaleString()}, ${formatEmailAddresses(emailToProcess?.from) || 'Unknown Sender'} wrote:
            </div>
            <div class="message-content" style="margin: 10px 0 0 10px; padding: 10px; border-left: 2px solid #e5e7eb; border: 1px solid #e5e7eb; border-radius: 4px; max-height: 300px; overflow-y: auto; color: #374151;">
              ${formatQuotedContent(emailContent)}
            </div>
          `;

          // Set the content in the compose area with proper structure
          const formattedContent = `
            <div class="compose-area" contenteditable="true" style="min-height: 100px; padding: 10px;">
              <div class="cursor-position" style="min-height: 20px; cursor: text;"><br/></div>
              ${quotedContent}
            </div>
          `;

          if (composeBodyRef.current) {
            composeBodyRef.current.innerHTML = formattedContent;

            // Place cursor at the beginning before the quoted content
            const selection = window.getSelection();
            const range = document.createRange();
            const firstDiv = composeBodyRef.current.querySelector('.cursor-position');
            if (firstDiv) {
              range.setStart(firstDiv, 0);
              range.collapse(true);
              selection?.removeAllRanges();
              selection?.addRange(range);
              (firstDiv as HTMLElement).focus();
            }

            // After setting the HTML content, add event listeners for scrolling
            const messageContents = composeBodyRef.current.querySelectorAll('.message-content');
            messageContents.forEach(container => {
              // Make sure the container is properly styled for scrolling
              (container as HTMLElement).style.maxHeight = '300px';
              (container as HTMLElement).style.overflowY = 'auto';
              (container as HTMLElement).style.border = '1px solid #e5e7eb';
              (container as HTMLElement).style.borderRadius = '4px';
              (container as HTMLElement).style.padding = '10px';

              // Ensure wheel events are properly handled
              if (!(container as HTMLElement).hasAttribute('data-scroll-handler-attached')) {
                container.addEventListener('wheel', (e: Event) => {
                  const wheelEvent = e as WheelEvent;
                  const target = e.currentTarget as HTMLElement;
                  
                  // Check if we're at the boundary of the scrollable area
                  const isAtBottom = target.scrollHeight - target.scrollTop <= target.clientHeight + 1;
                  const isAtTop = target.scrollTop <= 0;
                  
                  // Only prevent default if we're not at the boundaries in the direction of scrolling
                  if ((wheelEvent.deltaY > 0 && !isAtBottom) || (wheelEvent.deltaY < 0 && !isAtTop)) {
                    e.stopPropagation();
                    e.preventDefault(); // Prevent the parent container from scrolling
                  }
                }, { passive: false });
                
                // Mark this element as having a scroll handler attached
                (container as HTMLElement).setAttribute('data-scroll-handler-attached', 'true');
              }
            });

            // Update compose state
            setComposeBody(formattedContent);
            setLocalContent(formattedContent);
            console.log('[DEBUG] Successfully set compose content with scrollable message area');
          }
        } catch (error) {
          console.error('[DEBUG] Error initializing compose content:', error);
          if (composeBodyRef.current) {
            const errorContent = `
              <div class="compose-area" contenteditable="true">
                <br/>
                <div style="color: #ef4444;">Error loading original message.</div>
                <div style="color: #64748b; font-size: 0.875rem; margin-top: 0.5rem;">
                  Technical details: ${error instanceof Error ? error.message : 'Unknown error'}
                </div>
              </div>
            `;
            composeBodyRef.current.innerHTML = errorContent;
            setComposeBody(errorContent);
            setLocalContent(errorContent);
          }
        } finally {
          setIsLoading(false);
        }
      };

      initializeContent();
    }
  }, [replyTo, forwardFrom, setComposeBody]);

  const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
    if (!e.currentTarget) return;
    const content = e.currentTarget.innerHTML;
    if (!content.trim()) {
      setLocalContent('');
      setComposeBody('');
    } else {
      setLocalContent(content);
      setComposeBody(content);
    }
    
    if (onBodyChange) {
      onBodyChange(content);
    }
    
    // Ensure scrolling and cursor behavior works after edits
    const messageContentDivs = e.currentTarget.querySelectorAll('.message-content');
    messageContentDivs.forEach(div => {
      // Make sure the div remains scrollable after input events
      (div as HTMLElement).style.maxHeight = '300px';
      (div as HTMLElement).style.overflowY = 'auto';
      (div as HTMLElement).style.border = '1px solid #e5e7eb';
      (div as HTMLElement).style.borderRadius = '4px';
      (div as HTMLElement).style.padding = '10px';
      
      // Ensure wheel events are properly handled
      if (!(div as HTMLElement).hasAttribute('data-scroll-handler-attached')) {
        div.addEventListener('wheel', (e: Event) => {
          const wheelEvent = e as WheelEvent;
          const target = e.currentTarget as HTMLElement;
          
          // Check if we're at the boundary of the scrollable area
          const isAtBottom = target.scrollHeight - target.scrollTop <= target.clientHeight + 1;
          const isAtTop = target.scrollTop <= 0;
          
          // Only prevent default if we're not at the boundaries in the direction of scrolling
          if ((wheelEvent.deltaY > 0 && !isAtBottom) || (wheelEvent.deltaY < 0 && !isAtTop)) {
            e.stopPropagation();
            e.preventDefault(); // Prevent the parent container from scrolling
          }
        }, { passive: false });
        
        // Mark this element as having a scroll handler attached
        (div as HTMLElement).setAttribute('data-scroll-handler-attached', 'true');
      }
    });
  };

  const handleSendEmail = async () => {
    if (!composeBodyRef.current) return;

    const composeArea = composeBodyRef.current.querySelector('.compose-area');
    if (!composeArea) return;

    const content = composeArea.innerHTML;
    if (!content.trim()) {
      console.error('Email content is empty');
      return;
    }

    try {
      const encodedContent = await encodeComposeContent(content);
      setComposeBody(encodedContent);
      await handleSend();
      setShowCompose(false);
    } catch (error) {
      console.error('Error sending email:', error);
    }
  };

  const handleFileAttachment = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return;
    
    const newAttachments: any[] = [];
    const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes
    const oversizedFiles: string[] = [];
    
    for (const file of e.target.files) {
      if (file.size > MAX_FILE_SIZE) {
        oversizedFiles.push(file.name);
        continue;
      }

      try {
        // Read file as base64
        const base64Content = await new Promise<string>((resolve) => {
          const reader = new FileReader();
          reader.onloadend = () => {
            const base64 = reader.result as string;
            resolve(base64.split(',')[1]); // Remove data URL prefix
          };
          reader.readAsDataURL(file);
        });

        newAttachments.push({
          name: file.name,
          type: file.type,
          content: base64Content,
          encoding: 'base64'
        });
      } catch (error) {
        console.error('Error processing attachment:', error);
      }
    }

    if (oversizedFiles.length > 0) {
      alert(`The following files exceed the 10MB size limit and were not attached:\n${oversizedFiles.join('\n')}`);
    }

    if (newAttachments.length > 0) {
      setAttachments([...attachments, ...newAttachments]);
    }
  };

  // Add focus handling for better UX
  const handleComposeAreaClick = (e: React.MouseEvent<HTMLDivElement>) => {
    // If the click is directly on the compose area and not on any child element
    if (e.target === e.currentTarget) {
      // Find the cursor position element
      const cursorPosition = e.currentTarget.querySelector('.cursor-position');
      if (cursorPosition) {
        // Focus the cursor position element
        (cursorPosition as HTMLElement).focus();
        
        // Set cursor at the beginning
        const selection = window.getSelection();
        const range = document.createRange();
        range.setStart(cursorPosition, 0);
        range.collapse(true);
        selection?.removeAllRanges();
        selection?.addRange(range);
      }
    }
  };

  if (!showCompose) return null;

  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 h-[90vh] bg-white rounded-xl shadow-xl flex flex-col mx-4">
        {/* Modal Header */}
        <div className="flex-none flex items-center justify-between px-6 py-3 border-b border-gray-200">
          <h3 className="text-lg font-semibold text-gray-900">
            {replyTo ? 'Reply' : forwardFrom ? 'Forward' : 'New Message'}
          </h3>
          <Button
            variant="ghost"
            size="icon"
            className="hover:bg-gray-100 rounded-full"
            onClick={onCancel}
          >
            <X className="h-5 w-5 text-gray-500" />
          </Button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-hidden">
          <div className="h-full flex flex-col p-6 space-y-4 overflow-y-auto">
            {/* To Field */}
            <div className="flex-none">
              <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-none 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 className="flex-none">
                <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 className="flex-none">
                <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 className="flex-none">
              <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 */}
            <div className="flex-1 min-h-[200px] flex flex-col">
              <Label htmlFor="message" className="flex-none block text-sm font-medium text-gray-700 mb-2">Message</Label>
              <div
                ref={composeBodyRef}
                contentEditable="true"
                onInput={handleInput}
                onClick={handleComposeAreaClick}
                className="flex-1 w-full bg-white border border-gray-300 rounded-md p-4 text-black overflow-y-auto focus:outline-none focus:ring-1 focus:ring-blue-500"
                style={{ 
                  direction: 'ltr',
                  maxHeight: 'calc(100vh - 400px)',
                  minHeight: '200px',
                  overflowY: 'auto',
                  scrollbarWidth: 'thin',
                  scrollbarColor: '#cbd5e0 #f3f4f6',
                  cursor: 'text'
                }}
                dir="ltr"
                spellCheck="true"
                role="textbox"
                aria-multiline="true"
                tabIndex={0}
                suppressContentEditableWarning={true}
              />
            </div>
          </div>
        </div>

        {/* Modal Footer */}
        <div className="flex-none 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={onCancel}
            >
              Cancel
            </Button>
            <Button
              className="bg-blue-600 text-white hover:bg-blue-700"
              onClick={handleSendEmail}
            >
              Send
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}