'use client';

import { useState, useRef, useEffect } 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 DOMPurify from 'isomorphic-dompurify';
import { Label } from '@/components/ui/label';

// Import sub-components
import ComposeEmailHeader from './ComposeEmailHeader';
import RichEmailEditor from './RichEmailEditor';

// Import from the centralized utils
import { 
  formatReplyEmail, 
  formatForwardedEmail, 
  formatEmailAddresses
} from '@/lib/utils/email-utils';
import { EmailMessage, EmailAddress } from '@/types/email';

/**
 * CENTRAL EMAIL COMPOSER COMPONENT
 * 
 * This is the unified, centralized email composer component used throughout the application.
 * It handles new emails, replies, and forwards with proper text direction.
 * 
 * All code that needs to compose emails should import this component from:
 * @/components/email/ComposeEmail
 */

// Define interface for the modern props
interface ComposeEmailProps {
  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>;
}

export default function ComposeEmail(props: ComposeEmailProps) {
  const { initialEmail, type = 'new', 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 [quotedContent, setQuotedContent] = useState<string>('');
  const [showCc, setShowCc] = useState<boolean>(false);
  const [showBcc, setShowBcc] = useState<boolean>(false);
  const [sending, setSending] = useState<boolean>(false);
  const [attachments, setAttachments] = useState<Array<{
    name: string;
    content: string;
    type: string;
  }>>([]);
  
  const editorRef = useRef<HTMLDivElement>(null);
  
  // Initialize the form when replying to or forwarding an email
  useEffect(() => {
    if (initialEmail && type !== 'new') {
      try {
        // Set recipients based on type
        if (type === 'reply' || type === 'reply-all') {
          // Get formatted data for reply
          const formatted = formatReplyEmail(initialEmail, type);
          
          // Set the recipients
          setTo(formatted.to);
          if (formatted.cc) {
            setCc(formatted.cc);
            setShowCc(true);
          }
          
          // Set subject
          setSubject(formatted.subject);
          
          // Set the quoted content (original email)
          setQuotedContent(formatted.content.html || formatted.content.text);
          
          // Start with empty content for the reply
          setEmailContent('');
        }
        else if (type === 'forward') {
          // Get formatted data for forward
          const formatted = formatForwardedEmail(initialEmail);
          
          // Set subject
          setSubject(formatted.subject);
          
          // Set the quoted content (original email)
          setQuotedContent(formatted.content.html || formatted.content.text);
          
          // Start with empty content for the forward
          setEmailContent('');
          
          // If the original email has attachments, we should include them
          if (initialEmail.attachments && initialEmail.attachments.length > 0) {
            const formattedAttachments = initialEmail.attachments.map(att => ({
              name: att.filename || 'attachment',
              type: att.contentType || 'application/octet-stream',
              content: att.content || ''
            }));
            setAttachments(formattedAttachments);
          }
        }
      } catch (error) {
        console.error('Error initializing compose form:', error);
      }
    }
  }, [initialEmail, type]);
  
  // Handle file attachments
  const handleAttachmentAdd = async (files: FileList) => {
    const newAttachments = Array.from(files).map(file => ({
      name: file.name,
      type: file.type,
      content: URL.createObjectURL(file)
    }));
    
    setAttachments(prev => [...prev, ...newAttachments]);
  };
  
  const handleAttachmentRemove = (index: number) => {
    setAttachments(prev => prev.filter((_, i) => i !== index));
  };
  
  // Handle sending email
  const handleSend = async () => {
    if (!to) {
      alert('Please specify at least one recipient');
      return;
    }
    
    setSending(true);
    
    try {
      // Combine the new content with the quoted content
      const fullContent = type !== 'new' 
        ? `${emailContent}<div class="quoted-content">${quotedContent}</div>`
        : emailContent;
      
      await onSend({
        to,
        cc: cc || undefined,
        bcc: bcc || undefined,
        subject,
        body: fullContent,
        attachments
      });
      
      // Reset form and close
      onClose();
    } catch (error) {
      console.error('Error sending email:', error);
      alert('Failed to send email. Please try again.');
    } finally {
      setSending(false);
    }
  };
  
  // Focus and scroll to top when opened
  useEffect(() => {
    setTimeout(() => {
      if (editorRef.current) {
        editorRef.current.focus();
        
        // Scroll to top
        const scrollElements = [
          editorRef.current,
          document.querySelector('.overflow-y-auto'),
          document.querySelector('.compose-email-body')
        ];
        
        scrollElements.forEach(el => {
          if (el instanceof HTMLElement) {
            el.scrollTop = 0;
          }
        });
      }
    }, 100);
  }, []);
  
  return (
    <div className="flex flex-col h-full max-h-[80vh]">
      <ComposeEmailHeader 
        type={type}
        onClose={onClose}
      />
      <div className="flex-1 overflow-y-auto p-4 compose-email-body">
        <div className="h-full flex flex-col p-4 space-y-2 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={to}
              onChange={(e) => setTo(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={cc}
                onChange={(e) => setCc(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={bcc}
                onChange={(e) => setBcc(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={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Enter subject"
              className="w-full mt-1 bg-white border-gray-300 text-gray-900"
            />
          </div>

          {/* Message Body - Simplified Editor */}
          <div className="flex-1 min-h-[200px] flex flex-col overflow-hidden">
            <Label htmlFor="message" className="flex-none block text-sm font-medium text-gray-700 mb-2">Message</Label>
            <div className="flex-1 border border-gray-300 rounded-md overflow-hidden">
              <div className="email-editor-container flex flex-col h-full">
                {/* Simple editor for new content */}
                <div 
                  ref={editorRef}
                  className="simple-editor p-3 min-h-[100px] outline-none" 
                  contentEditable={true}
                  dangerouslySetInnerHTML={{ __html: emailContent }}
                  onInput={(e) => setEmailContent(e.currentTarget.innerHTML)}
                />
                
                {/* Quoted content from original email */}
                {quotedContent && (
                  <div className="quoted-email-content p-3 border-t border-gray-200 bg-gray-50">
                    <div 
                      className="email-quoted-content" 
                      dangerouslySetInnerHTML={{ __html: quotedContent }}
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
          
          {/* Attachments */}
          {attachments.length > 0 && (
            <div className="border rounded-md p-3 mt-4">
              <h3 className="text-sm font-medium mb-2 text-gray-700">Attachments</h3>
              <div className="space-y-2">
                {attachments.map((file, index) => (
                  <div key={index} className="flex items-center justify-between text-sm border rounded p-2">
                    <span className="truncate max-w-[200px] text-gray-800">{file.name}</span>
                    <Button 
                      variant="ghost"
                      size="sm"
                      onClick={() => handleAttachmentRemove(index)}
                      className="h-6 w-6 p-0 text-gray-500 hover:text-gray-700"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
      {/* Modal Footer - now inside the main modal container and visually attached */}
      <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={(e) => {
              if (e.target.files && e.target.files.length > 0) {
                handleAttachmentAdd(e.target.files);
              }
            }}
          />
          <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>
          {sending && <span className="text-xs text-gray-500 ml-2">Preparing attachment...</span>}
        </div>
        <div className="flex items-center gap-3">
          <Button 
            variant="ghost"
            className="text-gray-600 hover:text-gray-700 hover:bg-gray-100"
            onClick={onClose}
            disabled={sending}
          >
            Cancel
          </Button>
          <Button
            className="bg-blue-600 text-white hover:bg-blue-700"
            onClick={handleSend}
            disabled={sending}
          >
            {sending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Sending...
              </>
            ) : (
              <>
                <SendHorizontal className="mr-2 h-4 w-4" />
                Send
              </>
            )}
          </Button>
        </div>
      </div>
      
      {/* Styles for email display */}
      <style jsx global>{`
        .simple-editor {
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
          font-size: 14px;
          line-height: 1.6;
          width: 100%;
          flex: 1;
        }
        
        .email-quoted-content {
          color: #505050;
          font-size: 13px;
          line-height: 1.5;
          border-left: 2px solid #ddd;
          padding-left: 10px;
          margin-top: 5px;
        }
        
        .email-quoted-content blockquote {
          margin: 5px 0;
          padding-left: 10px;
          border-left: 2px solid #ddd;
        }
        
        .email-quoted-content img {
          max-width: 100%;
          height: auto;
        }
        
        .email-quoted-content table {
          border-collapse: collapse;
          width: 100%;
          max-width: 100%;
          margin-bottom: 1rem;
        }
        
        .email-quoted-content th,
        .email-quoted-content td {
          padding: 5px;
          border: 1px solid #ddd;
        }
        
        .email-quoted-content th {
          background-color: #f8f9fa;
          font-weight: 600;
          text-align: left;
        }
      `}</style>
    </div>
  );
} 