'use client';

import { useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { X, Paperclip, ChevronDown, ChevronUp, SendHorizontal } from 'lucide-react';
import { Email } from '@/app/courrier/page';

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;
  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 [sending, setSending] = useState(false);
  const editorRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  if (!showCompose) return null;

  const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
    const content = e.currentTarget.innerHTML;
    setComposeBody(content);
    if (onBodyChange) {
      onBodyChange(content);
    }
  };

  const handleSendEmail = async () => {
    if (!composeTo.trim()) {
      alert('Please enter a recipient');
      return;
    }

    setSending(true);
    try {
      // Prepare email data for sending
      const emailData = {
        to: composeTo,
        cc: composeCc,
        bcc: composeBcc,
        subject: composeSubject,
        body: composeBody,
        attachments: attachments
      };

      // Call the provided onSend function
      await onSend(emailData);
      
      // Reset the form
      onCancel();
    } catch (error) {
      console.error('Error sending email:', error);
      alert('Failed to send email. Please try again.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <Card className="w-full max-w-3xl bg-white shadow-lg">
        <CardHeader className="flex flex-row items-center justify-between p-4 border-b">
          <CardTitle className="text-lg font-medium">
            {replyTo ? 'Reply' : forwardFrom ? 'Forward' : 'New Message'}
          </CardTitle>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="h-4 w-4" />
          </Button>
        </CardHeader>
        <CardContent className="p-4 space-y-4">
          <div className="space-y-2">
            <div className="flex items-center">
              <span className="w-20 text-sm text-gray-500">To:</span>
              <Input 
                value={composeTo} 
                onChange={(e) => setComposeTo(e.target.value)}
                placeholder="recipient@example.com"
                className="border-0 focus-visible:ring-0"
              />
            </div>

            {showCc && (
              <div className="flex items-center">
                <span className="w-20 text-sm text-gray-500">Cc:</span>
                <Input 
                  value={composeCc} 
                  onChange={(e) => setComposeCc(e.target.value)}
                  placeholder="cc@example.com"
                  className="border-0 focus-visible:ring-0"
                />
              </div>
            )}

            {showBcc && (
              <div className="flex items-center">
                <span className="w-20 text-sm text-gray-500">Bcc:</span>
                <Input 
                  value={composeBcc} 
                  onChange={(e) => setComposeBcc(e.target.value)}
                  placeholder="bcc@example.com"
                  className="border-0 focus-visible:ring-0"
                />
              </div>
            )}

            <div className="flex items-center">
              <span className="w-20 text-sm text-gray-500">Subject:</span>
              <Input 
                value={composeSubject} 
                onChange={(e) => setComposeSubject(e.target.value)}
                placeholder="Subject"
                className="border-0 focus-visible:ring-0"
              />
            </div>

            <div className="flex items-center text-xs text-blue-600 space-x-4 ml-20">
              {!showCc && (
                <button 
                  type="button" 
                  onClick={() => setShowCc(true)}
                  className="hover:underline"
                >
                  Add Cc
                </button>
              )}
              {!showBcc && (
                <button 
                  type="button" 
                  onClick={() => setShowBcc(true)}
                  className="hover:underline"
                >
                  Add Bcc
                </button>
              )}
            </div>
          </div>

          <div 
            className="border rounded p-3 min-h-[200px] max-h-[400px] overflow-auto"
            contentEditable 
            dangerouslySetInnerHTML={{ __html: composeBody }}
            onInput={handleInput}
            ref={editorRef}
          />

          {attachments.length > 0 && (
            <div className="border-t pt-2">
              <h4 className="text-sm text-gray-500 mb-2">Attachments</h4>
              <div className="flex flex-wrap gap-2">
                {attachments.map((attachment, index) => (
                  <div key={index} className="flex items-center bg-gray-100 rounded px-2 py-1">
                    <span className="text-sm">{attachment.name}</span>
                    <button 
                      type="button" 
                      className="ml-2 text-gray-400 hover:text-gray-600"
                      onClick={() => {
                        const newAttachments = [...attachments];
                        newAttachments.splice(index, 1);
                        setAttachments(newAttachments);
                      }}
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
        <CardFooter className="flex justify-between p-4 border-t">
          <div className="flex space-x-2">
            <input
              type="file"
              className="hidden"
              ref={fileInputRef}
              onChange={(e) => {
                if (e.target.files?.length) {
                  const newAttachments = Array.from(e.target.files).map(file => ({
                    name: file.name,
                    type: file.type,
                    content: URL.createObjectURL(file),
                    file
                  }));
                  setAttachments([...attachments, ...newAttachments]);
                }
              }}
              multiple
            />
            <Button 
              variant="ghost" 
              size="sm"
              onClick={() => fileInputRef.current?.click()}
            >
              <Paperclip className="h-4 w-4 mr-1" />
              Attach
            </Button>
          </div>
          <Button 
            onClick={handleSendEmail}
            disabled={sending || !composeTo.trim()}
            className="bg-blue-600 hover:bg-blue-700 text-white"
          >
            {sending ? (
              <>Sending...</>
            ) : (
              <>
                <SendHorizontal className="h-4 w-4 mr-1" />
                Send
              </>
            )}
          </Button>
        </CardFooter>
      </Card>
    </div>
  );
} 