'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 { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import DOMPurify from 'isomorphic-dompurify';
import { formatEmailForReply, formatEmailForForward } from '@/lib/email-formatter';

interface EmailObject {
  id?: string;
  from?: string;
  fromName?: string;
  to?: string;
  subject?: string;
  content?: string;
  html?: string;
  text?: string;
  body?: string;
  date?: string;
  read?: boolean;
  starred?: boolean;
  attachments?: { name: string; url: string }[];
  folder?: string;
  cc?: string;
  bcc?: string;
}

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: any) => Promise<void>;
  onCancel: () => void;
  replyTo?: EmailObject | null;
  forwardFrom?: EmailObject | 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,
  replyTo,
  forwardFrom,
  onSend,
  onCancel
}: ComposeEmailProps) {
  const [isSending, setIsSending] = useState(false);
  const editorRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const composeBodyRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (editorRef.current) {
      editorRef.current.focus();
    }
  }, [showCompose]);

  // Initialize content when replying or forwarding
  useEffect(() => {
    // Initialize reply if replyTo is provided
    if (replyTo) {
      // For reply/reply-all
      const formattedEmail = formatEmailForReply(replyTo as any, 'reply');
      setComposeTo(formattedEmail.to);
      setComposeSubject(formattedEmail.subject);
      
      // Use the body but preserve the original UI styling
      // Extract just the content portion from the client formatter output 
      // and apply the original styling
      let bodyContent = formattedEmail.body;
      
      // Apply DOMPurify to the content for safety
      bodyContent = DOMPurify.sanitize(bodyContent, {
        ADD_TAGS: ['style'],
        FORBID_TAGS: ['script', 'iframe']
      });
      
      setComposeBody(bodyContent);
      
      // Show CC if needed for reply-all
      if (formattedEmail.cc) {
        setComposeCc(formattedEmail.cc);
        setShowCc(true);
      }
    } else if (forwardFrom) {
      // Initialize forward email if forwardFrom is provided
      initializeForwardedEmail(forwardFrom);
    }
  }, [replyTo, forwardFrom]);

  // Initialize forwarded email content
  const initializeForwardedEmail = async (email: any) => {
    if (!email) return;

    console.log('Initializing forwarded email:', email);
    
    // Use our client-side formatter
    const formattedEmail = formatEmailForForward(email);
    
    // Set the formatted subject with Fwd: prefix
    setComposeSubject(formattedEmail.subject);
    
    // Create header for forwarded email - use the original styling
    const headerHtml = formattedEmail.headerHtml;
    
    // Prepare content
    let contentHtml = '<div style="color: #666; font-style: italic; padding: 15px; border: 1px dashed #ccc; margin: 10px 0; text-align: center; background-color: #f9f9f9;">No content available</div>';
    
    if (email.content) {
      // Sanitize the content
      contentHtml = DOMPurify.sanitize(email.content, {
        ADD_TAGS: ['style'],
        FORBID_TAGS: ['script', 'iframe']
      });
    } else if (email.html) {
      contentHtml = DOMPurify.sanitize(email.html, {
        ADD_TAGS: ['style'],
        FORBID_TAGS: ['script', 'iframe']
      });
    } else if (email.text) {
      contentHtml = `<pre>${email.text}</pre>`;
    } else if (email.body) {
      contentHtml = DOMPurify.sanitize(email.body, {
        ADD_TAGS: ['style'],
        FORBID_TAGS: ['script', 'iframe']
      });
    }
    
    // Set body with header and content, preserving the original UI layout
    setComposeBody(`
      ${headerHtml}
      <div style="margin-top: 10px;">
        ${contentHtml}
      </div>
    `);
  };

  if (!showCompose) return null;

  const handleFileSelection = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const newAttachments = Array.from(e.target.files).map(file => ({
        name: file.name,
        type: file.type,
        size: file.size,
        file
      }));
      setAttachments([...attachments, ...newAttachments]);
    }
  };

  // Body input area
  const renderBodyInput = () => (
    <div 
      className="min-h-[200px] max-h-[400px] overflow-y-auto p-3 bg-white border border-gray-300 rounded-md"
      contentEditable 
      dangerouslySetInnerHTML={{ __html: composeBody || '' }}
      onInput={(e) => {
        const target = e.target as HTMLDivElement;
        setComposeBody(target.innerHTML);
      }}
      ref={composeBodyRef}
      style={{ direction: 'ltr' }}
    />
  );

  return (
    <Card className={`fixed inset-0 z-50 mx-auto my-8 max-w-3xl rounded-md bg-white shadow-lg flex flex-col ${showCompose ? 'block' : 'hidden'}`} style={{ maxHeight: 'calc(100vh - 4rem)' }}>
      <CardHeader className="bg-white p-4 border-b">
        <div className="flex justify-between items-center">
          <CardTitle className="text-xl font-semibold text-gray-800">{replyTo ? 'Reply' : forwardFrom ? 'Forward' : 'New Message'}</CardTitle>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="h-5 w-5" />
          </Button>
        </div>
      </CardHeader>
      <CardContent className="flex-grow overflow-auto p-4 bg-white">
        <div className="space-y-4">
          <div className="flex items-center">
            <span className="w-16 text-sm font-medium text-gray-600">To:</span>
            <Input 
              className="flex-1 bg-white" 
              value={composeTo} 
              onChange={(e) => setComposeTo(e.target.value)} 
            />
          </div>

          {showCc && (
            <div className="flex items-center">
              <span className="w-16 text-sm font-medium text-gray-600">Cc:</span>
              <Input 
                className="flex-1 bg-white" 
                value={composeCc} 
                onChange={(e) => setComposeCc(e.target.value)} 
              />
            </div>
          )}

          {showBcc && (
            <div className="flex items-center">
              <span className="w-16 text-sm font-medium text-gray-600">Bcc:</span>
              <Input 
                className="flex-1 bg-white" 
                value={composeBcc} 
                onChange={(e) => setComposeBcc(e.target.value)} 
              />
            </div>
          )}

          <div className="flex">
            <Button variant="link" onClick={() => setShowCc(!showCc)} className="p-0 h-auto text-sm">
              {showCc ? (
                <ChevronUp className="h-4 w-4 mr-1" />
              ) : (
                <ChevronDown className="h-4 w-4 mr-1" />
              )}
              Cc
            </Button>
            <Button variant="link" onClick={() => setShowBcc(!showBcc)} className="p-0 h-auto text-sm ml-4">
              {showBcc ? (
                <ChevronUp className="h-4 w-4 mr-1" />
              ) : (
                <ChevronDown className="h-4 w-4 mr-1" />
              )}
              Bcc
            </Button>
          </div>

          <div className="flex items-center">
            <span className="w-16 text-sm font-medium text-gray-600">Subject:</span>
            <Input 
              className="flex-1 bg-white" 
              value={composeSubject} 
              onChange={(e) => setComposeSubject(e.target.value)} 
            />
          </div>

          {renderBodyInput()}

          {attachments.length > 0 && (
            <div className="mt-4">
              <h4 className="text-sm font-medium text-gray-600 mb-2">Attachments:</h4>
              <div className="flex flex-wrap gap-2">
                {attachments.map((file, index) => (
                  <div key={index} className="flex items-center bg-gray-100 rounded-md p-2">
                    <Paperclip className="h-4 w-4 mr-2 text-gray-500" />
                    <span className="text-sm mr-2">{file.name}</span>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-5 w-5 p-0 hover:bg-gray-200"
                      onClick={() => {
                        const newAttachments = [...attachments];
                        newAttachments.splice(index, 1);
                        setAttachments(newAttachments);
                      }}
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </CardContent>
      <CardFooter className="flex justify-between p-4 border-t bg-white">
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => fileInputRef.current?.click()}
            className="flex items-center gap-1 bg-white"
          >
            <Paperclip className="h-4 w-4" />
            Attach
          </Button>
          <input
            type="file"
            ref={fileInputRef}
            className="hidden"
            onChange={handleFileSelection}
            multiple
          />
        </div>
        <Button
          onClick={handleSend}
          disabled={isSending || !composeTo.trim()}
          className="flex items-center gap-2"
        >
          {isSending ? (
            <>
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              Sending...
            </>
          ) : (
            <>
              <SendHorizontal className="h-4 w-4 mr-1" />
              Send
            </>
          )}
        </Button>
      </CardFooter>
    </Card>
  );
} 