'use client';

import React, { useMemo } from 'react';
import { EmailContent } from '@/types/email';
import { formatEmailContent } from '@/lib/utils/email-content';

interface EmailContentDisplayProps {
  content: EmailContent | string | null;
  className?: string;
  showQuotedText?: boolean;
  type?: 'html' | 'text' | 'auto';
  debug?: boolean;
}

/**
 * Unified component for displaying email content in a consistent way
 * This handles both HTML and plain text content with proper styling and RTL support
 */
const EmailContentDisplay: React.FC<EmailContentDisplayProps> = ({
  content,
  className = '',
  showQuotedText = true,
  type = 'auto',
  debug = false
}) => {
  // Process content if provided
  const processedContent = useMemo(() => {
    if (!content) {
      return { __html: '<div class="email-content-empty">No content available</div>' };
    }
    
    try {
      let formattedContent: string;
      
      // If it's a string, we need to determine if it's HTML or plain text
      if (typeof content === 'string') {
        formattedContent = formatEmailContent({ content });
      } 
      // If it's an EmailContent object
      else {
        formattedContent = formatEmailContent({ content });
      }
      
      return { __html: formattedContent };
    } catch (error) {
      console.error('Error processing email content:', error);
      return { __html: '<div class="email-content-error">Error displaying email content</div>' };
    }
  }, [content]);
  
  // Handle quoted text display
  const displayHTML = useMemo(() => {
    if (!showQuotedText) {
      // Hide quoted text (usually in blockquotes)
      // This is simplified - a more robust approach would parse and handle
      // quoted sections more intelligently
      const htmlWithoutQuotes = processedContent.__html.replace(/<blockquote[^>]*>[\s\S]*?<\/blockquote>/gi, 
        '<div class="text-gray-400">[Quoted text hidden]</div>');
      return { __html: htmlWithoutQuotes };
    }
    return processedContent;
  }, [processedContent, showQuotedText]);
  
  return (
    <div className={`email-content-display ${className}`}>
      <div 
        className="email-content-inner"
        dangerouslySetInnerHTML={displayHTML} 
      />
      
      {/* Debug output if enabled */}
      {debug && (
        <div className="mt-4 p-2 text-xs bg-gray-100 border rounded">
          <p><strong>Content Type:</strong> {typeof content === 'string' ? 'Text' : 'HTML'}</p>
          <p><strong>HTML Length:</strong> {typeof content === 'string' ? content.length : content?.html?.length || 0}</p>
          <p><strong>Text Length:</strong> {typeof content === 'string' ? 0 : content?.text?.length || 0}</p>
          <p><strong>Has Forwarded Header:</strong> {typeof content === 'string' ? 
            content.includes('Forwarded Message') : 
            (content?.html?.includes('Forwarded Message') || content?.text?.includes('Forwarded Message')) ? 'Yes' : 'No'
          }</p>
        </div>
      )}
      
      <style jsx>{`
        .email-content-display {
          width: 100%;
        }
        
        .email-content-inner img {
          max-width: 100%;
          height: auto;
        }
        
        .email-content-inner blockquote {
          margin: 10px 0;
          padding-left: 15px;
          border-left: 2px solid #ddd;
          color: #666;
          background-color: #f9f9f9;
          border-radius: 4px;
        }
        
        /* RTL blockquote styling will be handled by the direction attribute now */
        [dir="rtl"] blockquote {
          padding-left: 0;
          padding-right: 15px;
          border-left: none;
          border-right: 2px solid #ddd;
        }
        
        /* Specific styling for forwarded email header */
        :global(.forwarded-email-header) {
          margin: 20px 0 10px 0 !important;
          color: #666 !important;
          font-family: Arial, sans-serif !important;
        }
        
        :global(.forwarded-email-header table) {
          margin-bottom: 10px !important;
          font-size: 14px !important;
          width: 100% !important;
          border-collapse: collapse !important;
        }
        
        :global(.forwarded-email-header td) {
          padding: 3px 5px !important;
          vertical-align: top !important;
        }
        
        :global(.forwarded-email-content) {
          margin-top: 15px !important;
        }
      `}</style>
    </div>
  );
};

export default EmailContentDisplay; 