'use client';

import { useState, useRef, useEffect } from 'react';
import { 
  X, Paperclip, SendHorizontal, Loader2, Plus, ChevronDown
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import DOMPurify from 'isomorphic-dompurify';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import RichTextEditor from '@/components/ui/rich-text-editor';
import { detectTextDirection } from '@/lib/utils/text-direction';

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

/**
 * Email composer component
 * Handles new emails, replies, and forwards with a clean UI
 */
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;
    fromAccount?: string;
    attachments?: Array<{
      name: string;
      content: string;
      type: string;
    }>;
  }) => Promise<void>;
  accounts?: Array<{
    id: string;
    email: string;
    display_name?: string;
  }>;
}

export default function ComposeEmail(props: ComposeEmailProps) {
  const { initialEmail, type = 'new', onClose, onSend, accounts = [] } = 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 [selectedAccount, setSelectedAccount] = useState<{
    id: string;
    email: string;
    display_name?: string;
  } | null>(accounts.length > 0 ? accounts[0] : null);
  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 content with original email
          const content = formatted.content.html || formatted.content.text;
          setEmailContent(content);
        }
        else if (type === 'forward') {
          // Get formatted data for forward
          const formatted = formatForwardedEmail(initialEmail);
          
          // Set subject
          setSubject(formatted.subject);
          
          // Set content with original email
          const content = formatted.content.html || formatted.content.text;
          setEmailContent(content);
          
          // If the original email has attachments, 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]);
  
  // Place cursor at beginning and ensure content is scrolled to top
  useEffect(() => {
    if (editorRef.current && type !== 'new') {
      // Small delay to ensure DOM is ready
      setTimeout(() => {
        if (editorRef.current) {
          // Focus the editor
          editorRef.current.focus();
          
          // Put cursor at the beginning
          const selection = window.getSelection();
          const range = document.createRange();
          range.setStart(editorRef.current, 0);
          range.collapse(true);
          selection?.removeAllRanges();
          selection?.addRange(range);
          
          // Also make sure editor container is scrolled to top
          editorRef.current.scrollTop = 0;
          
          // Find parent scrollable containers and scroll them to top
          let parent = editorRef.current.parentElement;
          while (parent) {
            if (parent.classList.contains('overflow-y-auto')) {
              parent.scrollTop = 0;
            }
            parent = parent.parentElement;
          }
        }
      }, 100);
    }
  }, [emailContent, 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 {
      await onSend({
        to,
        cc: cc || undefined,
        bcc: bcc || undefined,
        subject,
        body: emailContent,
        fromAccount: selectedAccount?.id,
        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);
    }
  };
  
  // Get compose title based on type
  const getComposeTitle = () => {
    switch(type) {
      case 'reply': return 'Reply';
      case 'reply-all': return 'Reply All';
      case 'forward': return 'Forward';
      default: return 'New Message';
    }
  };
  
  return (
    <div className="flex flex-col h-full max-h-[80vh] bg-white border rounded-md shadow-md">
      {/* Header */}
      <div className="flex items-center justify-between p-3 border-b bg-gray-50">
        <h2 className="text-lg font-medium text-gray-800">{getComposeTitle()}</h2>
        <Button variant="ghost" size="icon" onClick={onClose}>
          <X className="h-5 w-5" />
        </Button>
      </div>
      
      {/* Email Form */}
      <div className="flex-1 overflow-y-auto bg-white">
        <div className="p-2 space-y-2">
          {/* From */}
          <div className="border-b pb-1">
            <div className="flex items-center">
              <span className="w-16 text-gray-700 font-medium">From:</span>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button 
                    variant="outline" 
                    className="w-full flex justify-between items-center h-8 px-2 py-1 text-left font-normal"
                  >
                    <span className="truncate">
                      {selectedAccount ? 
                        (selectedAccount.display_name ? 
                          `${selectedAccount.display_name} <${selectedAccount.email}>` : 
                          selectedAccount.email) : 
                        'Select account'}
                    </span>
                    <ChevronDown className="h-4 w-4 opacity-50" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="start" className="w-[240px]">
                  <DropdownMenuLabel>Select account</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  {accounts.length > 0 ? (
                    accounts.map(account => (
                      <DropdownMenuItem 
                        key={account.id}
                        onClick={() => setSelectedAccount(account)}
                        className="cursor-pointer"
                      >
                        {account.display_name ? 
                          `${account.display_name} <${account.email}>` : 
                          account.email}
                      </DropdownMenuItem>
                    ))
                  ) : (
                    <DropdownMenuItem disabled>No accounts available</DropdownMenuItem>
                  )}
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
          
          {/* Recipients */}
          <div className="border-b pb-1">
            <div className="flex items-center">
              <span className="w-16 text-gray-700 font-medium">To:</span>
              <Input 
                type="text"
                value={to}
                onChange={(e) => setTo(e.target.value)}
                placeholder="recipient@example.com"
                className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
              />
            </div>
            
            {showCc && (
              <div className="flex items-center">
                <span className="w-16 text-gray-700 font-medium">Cc:</span>
                <Input 
                  type="text"
                  value={cc}
                  onChange={(e) => setCc(e.target.value)}
                  placeholder="cc@example.com"
                  className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
                />
              </div>
            )}
            
            {showBcc && (
              <div className="flex items-center">
                <span className="w-16 text-gray-700 font-medium">Bcc:</span>
                <Input 
                  type="text"
                  value={bcc}
                  onChange={(e) => setBcc(e.target.value)}
                  placeholder="bcc@example.com"
                  className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
                />
              </div>
            )}
            
            {/* CC/BCC Toggle Links */}
            <div className="flex gap-3 ml-16">
              {!showCc && (
                <button 
                  className="text-blue-600 text-sm hover:underline"
                  onClick={() => setShowCc(true)}
                >
                  Add Cc
                </button>
              )}
              
              {!showBcc && (
                <button 
                  className="text-blue-600 text-sm hover:underline"
                  onClick={() => setShowBcc(true)}
                >
                  Add Bcc
                </button>
              )}
            </div>
          </div>
          
          {/* Subject */}
          <div className="border-b pb-1">
            <div className="flex items-center">
              <span className="w-16 text-gray-700 font-medium">Subject:</span>
              <Input 
                type="text"
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                placeholder="Subject"
                className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
              />
            </div>
          </div>
          
          {/* Message Body */}
          <RichTextEditor
            ref={editorRef}
            initialContent={emailContent}
            initialDirection={detectTextDirection(emailContent)}
            onChange={setEmailContent}
            className="min-h-[320px] border rounded-md bg-white text-gray-800 flex-1"
            placeholder="Write your message here..."
          />
          
          {/* Attachments */}
          {attachments.length > 0 && (
            <div className="p-2 border rounded-md bg-gray-50">
              <div className="text-sm font-medium mb-1 text-gray-700">Attachments:</div>
              {attachments.map((file, index) => (
                <div key={index} className="flex items-center justify-between text-sm py-1">
                  <span className="truncate mr-2 text-gray-800">{file.name}</span>
                  <Button 
                    variant="ghost"
                    size="sm"
                    onClick={() => handleAttachmentRemove(index)}
                    className="h-6 w-6 p-0"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
      
      {/* Footer */}
      <div className="border-t p-3 flex items-center justify-between bg-gray-50">
        <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" className="flex items-center cursor-pointer">
            <Button 
              variant="outline" 
              size="sm"
              className="flex items-center gap-1"
            >
              <Paperclip className="h-4 w-4" />
              <span>Attach</span>
            </Button>
          </label>
        </div>
        
        <div className="flex items-center gap-2">
          <Button 
            variant="outline"
            onClick={onClose}
            className="border-gray-300 text-gray-700"
          >
            Cancel
          </Button>
          
          <Button
            variant="default"
            onClick={handleSend}
            disabled={sending}
            className="bg-blue-600 hover:bg-blue-700 text-white"
          >
            {sending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Sending
              </>
            ) : (
              <>
                <SendHorizontal className="h-4 w-4" />
                Send
              </>
            )}
          </Button>
        </div>
      </div>
      
      {/* Styles for email content */}
      <style jsx global>{`
        [contenteditable] {
          -webkit-user-modify: read-write-plaintext-only;
          overflow-wrap: break-word;
          -webkit-line-break: after-white-space;
          -webkit-user-select: text;
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
          font-size: 14px;
          line-height: 1.5;
          color: #333;
          background-color: #fff;
        }
        
        [contenteditable]:focus {
          outline: none;
        }
        
        [contenteditable] blockquote {
          margin: 10px 0;
          padding-left: 15px;
          border-left: 2px solid #ddd;
          color: #666;
        }
        
        [contenteditable] img {
          max-width: 100%;
          height: auto;
        }
        
        [contenteditable] table {
          border-collapse: collapse;
          width: 100%;
          max-width: 100%;
          margin-bottom: 1rem;
        }
        
        [contenteditable] th,
        [contenteditable] td {
          padding: 5px;
          border: 1px solid #ddd;
        }
        
        [contenteditable] th {
          background-color: #f8f9fa;
          font-weight: 600;
          text-align: left;
        }
        
        /* Forwarded message styles */
        .email-original-content {
          margin-top: 20px;
          color: #505050;
        }
      `}</style>
    </div>
  );
} 