'use client';

import { useRef, useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Paperclip, X } from 'lucide-react';
import { Textarea } from '@/components/ui/textarea';
import { decodeComposeContent, encodeComposeContent } from '@/lib/compose-mime-decoder';
import { Email } from '@/app/courrier/page';
import mime from 'mime';
import { simpleParser } from 'mailparser';

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: Email) => void;
  onCancel: () => void;
  onBodyChange?: (body: string) => void;
  initialTo?: string;
  initialSubject?: string;
  initialBody?: string;
  initialCc?: string;
  initialBcc?: string;
  replyTo?: Email | null;
  forwardFrom?: Email | 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,
  onSend,
  onCancel,
  onBodyChange,
  initialTo,
  initialSubject,
  initialBody,
  initialCc,
  initialBcc,
  replyTo,
  forwardFrom
}: ComposeEmailProps) {
  const composeBodyRef = useRef<HTMLDivElement>(null);
  const [localContent, setLocalContent] = useState('');
  const [isInitialized, setIsInitialized] = useState(false);
  
  useEffect(() => {
    if (composeBodyRef.current && !isInitialized) {
      let content = '';
      
      if (replyTo || forwardFrom) {
        const originalContent = replyTo?.body || forwardFrom?.body || '';
        
        fetch('/api/parse-email', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ emailContent: originalContent }),
        })
        .then(response => response.json())
        .then(parsed => {
          content = `
            <div class="compose-area" contenteditable="true" style="min-height: 100px; padding: 10px; color: #000000;">
              <br/><br/><br/>
              ${forwardFrom ? `
                <div style="border-top: 1px solid #e5e7eb; padding-top: 20px; margin-top: 20px; color: #6b7280; font-size: 0.875rem;">
                  ---------- Forwarded message ---------<br/>
                  From: ${forwardFrom.from}<br/>
                  Date: ${new Date(forwardFrom.date).toLocaleString()}<br/>
                  Subject: ${forwardFrom.subject}<br/>
                  To: ${forwardFrom.to}<br/>
                  ${forwardFrom.cc ? `Cc: ${forwardFrom.cc}<br/>` : ''}
                  <br/>
                  ${parsed.html || parsed.text}
                </div>
              ` : `
                <div style="border-top: 1px solid #e5e7eb; padding-top: 20px; margin-top: 20px; color: #6b7280; font-size: 0.875rem;">
                  On ${new Date(replyTo?.date || '').toLocaleString()}, ${replyTo?.from} wrote:
                </div>
                <blockquote style="margin: 0; padding-left: 1em; border-left: 2px solid #e5e7eb; color: #6b7280;">
                  ${parsed.html || parsed.text}
                </blockquote>
              `}
            </div>
          `;

          if (composeBodyRef.current) {
            composeBodyRef.current.innerHTML = content;
            setIsInitialized(true);
            
            // Place cursor at the beginning of the compose area
            const composeArea = composeBodyRef.current.querySelector('.compose-area');
            if (composeArea) {
              const range = document.createRange();
              const sel = window.getSelection();
              range.setStart(composeArea, 0);
              range.collapse(true);
              sel?.removeAllRanges();
              sel?.addRange(range);
              (composeArea as HTMLElement).focus();
            }
          }
        })
        .catch(error => {
          console.error('Error parsing email:', error);
        });
      } else {
        content = `<div class="compose-area" contenteditable="true" style="min-height: 100px; padding: 10px; color: #000000;"></div>`;
        composeBodyRef.current.innerHTML = content;
        setIsInitialized(true);
        
        const composeArea = composeBodyRef.current.querySelector('.compose-area');
        if (composeArea) {
          const range = document.createRange();
          const sel = window.getSelection();
          range.setStart(composeArea, 0);
          range.collapse(true);
          sel?.removeAllRanges();
          sel?.addRange(range);
          (composeArea as HTMLElement).focus();
        }
      }
    }
  }, [composeBody, replyTo, forwardFrom, isInitialized]);

  return (
    <div>
      {/* Rest of the component code remains unchanged */}
    </div>
  );
}