'use client';

import { useState, useEffect } from 'react';
import ComposeEmail from './ComposeEmail';
import { EmailMessage } from '@/types/email'; 
import { 
  formatReplyEmail,
  formatForwardedEmail
} from '@/lib/utils/email-utils';

interface ComposeEmailAdapterProps {
  initialEmail?: EmailMessage | null;
  type?: 'new' | 'reply' | 'reply-all' | 'forward';
  onClose: () => void;
  onSend: (emailData: {
    to: string;
    cc?: string;
    bcc?: string;
    subject: string;
    body: string;
    attachments?: Array<{
      name: string;
      content: string;
      type: string;
    }>;
  }) => Promise<void>;
}

/**
 * Adapter component that converts between the new EmailMessage format
 * and the format expected by the legacy ComposeEmail component
 */
export default function ComposeEmailAdapter({
  initialEmail,
  type = 'new',
  onClose,
  onSend
}: ComposeEmailAdapterProps) {
  // Convert the new EmailMessage format to the old format
  const [adaptedEmail, setAdaptedEmail] = useState<any | null>(null);
  
  useEffect(() => {
    if (!initialEmail) {
      setAdaptedEmail(null);
      return;
    }
    
    try {
      console.log('ComposeEmailAdapter: Processing email for', type, initialEmail);
      
      // For reply or forward, use the email formatting utilities
      if (type === 'reply' || type === 'reply-all') {
        const formatted = formatReplyEmail(initialEmail, type);
        console.log('ComposeEmailAdapter: Formatted reply', formatted);
        
        // Create an object suitable for the legacy ComposeEmail component
        const adapted = {
          id: initialEmail.id,
          subject: formatted.subject,
          // Format to/cc as expected by ComposeEmail
          to: formatted.to || initialEmail.from, // Will set recipient to original sender
          cc: formatted.cc,
          // Include the original content for quoting
          content: formatted.content?.html || formatted.content?.text || '',
          html: formatted.content?.html,
          text: formatted.content?.text,
          // Copy over attachments if needed
          attachments: initialEmail.attachments || []
        };
        
        setAdaptedEmail(adapted);
      } 
      else if (type === 'forward') {
        const formatted = formatForwardedEmail(initialEmail);
        console.log('ComposeEmailAdapter: Formatted forward', formatted);
        
        // Create an object suitable for the legacy ComposeEmail component
        const adapted = {
          id: initialEmail.id,
          subject: formatted.subject,
          // Forward doesn't pre-fill recipients
          to: '',
          cc: '',
          // Include the forwarded content
          content: formatted.content?.html || formatted.content?.text || '',
          html: formatted.content?.html,
          text: formatted.content?.text,
          // Copy over attachments
          attachments: initialEmail.attachments || []
        };
        
        setAdaptedEmail(adapted);
      }
      else {
        // For new emails, just create a minimal template
        setAdaptedEmail({
          subject: '',
          to: '',
          cc: '',
          content: '',
          html: '',
          text: '',
          attachments: []
        });
      }
    } catch (error) {
      console.error('Error adapting email for ComposeEmail:', error);
      // Provide a fallback minimal email
      setAdaptedEmail({
        subject: initialEmail?.subject || '',
        to: initialEmail?.from || '',
        cc: '',
        content: '',
        html: '',
        text: '',
        attachments: []
      });
    }
  }, [initialEmail, type]);
  
  // If still adapting, show loading
  if (initialEmail && !adaptedEmail) {
    return <div>Loading email...</div>;
  }
  
  // Pass the adapted email to the original ComposeEmail component
  return (
    <ComposeEmail
      initialEmail={adaptedEmail}
      type={type}
      onClose={onClose}
      onSend={onSend}
    />
  );
} 