"""
Email utility functions for ScholarPress.
"""

from flask import current_app, render_template_string
from flask_mail import Message
from app import mail
from threading import Thread


def send_async_email(app, msg):
    """Send email asynchronously."""
    with app.app_context():
        try:
            mail.send(msg)
        except Exception as e:
            print(f"Error sending email: {e}")


def send_email(subject, recipient, body_html, body_text=None):
    """Send an email."""
    msg = Message(subject=subject, recipients=[recipient])
    msg.html = body_html
    if body_text:
        msg.body = body_text
    
    # Send asynchronously to avoid blocking
    Thread(
        target=send_async_email, 
        args=(current_app._get_current_object(), msg)
    ).start()


def send_submission_confirmation(submission, site_url):
    """Send confirmation email when a submission is received."""
    subject = f"Research Submission Received - {submission.tracking_id}"
    
    body_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: #1a365d; color: white; padding: 20px; text-align: center; }}
            .content {{ padding: 20px; background: #f9f9f9; }}
            .tracking-id {{ font-size: 24px; font-weight: bold; color: #1a365d; text-align: center; padding: 20px; background: #e8f4f8; margin: 20px 0; }}
            .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
            a {{ color: #2563eb; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>ScholarPress</h1>
            </div>
            <div class="content">
                <h2>Submission Received</h2>
                <p>Dear Author,</p>
                <p>Thank you for submitting your research to ScholarPress. We have received your manuscript:</p>
                <p><strong>Title:</strong> {submission.title}</p>
                <p><strong>Journal:</strong> {submission.journal.name}</p>
                
                <div class="tracking-id">
                    Your Tracking ID: {submission.tracking_id}
                </div>
                
                <p>You can track your submission status at any time using this tracking ID:</p>
                <p><a href="{site_url}/submit/track?tracking_id={submission.tracking_id}">Track Your Submission</a></p>
                
                <p>Our editorial team will review your submission and you will be notified of any updates via email.</p>
                
                <p>Best regards,<br>The ScholarPress Editorial Team</p>
            </div>
            <div class="footer">
                <p>This is an automated message. Please do not reply directly to this email.</p>
            </div>
        </div>
    </body>
    </html>
    """
    
    send_email(subject, submission.contact_email, body_html)


def send_submission_status_update(submission, old_status, new_status, notes, site_url):
    """Send email when submission status changes."""
    status_messages = {
        'in_review': 'Your submission is now under review by our editorial team.',
        'accepted': 'Congratulations! Your submission has been accepted for publication.',
        'declined': 'After careful review, we regret to inform you that your submission has not been accepted.'
    }
    
    subject = f"Submission Update - {submission.tracking_id}"
    status_message = status_messages.get(new_status, f'Your submission status has been updated to: {new_status}')
    
    body_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: #1a365d; color: white; padding: 20px; text-align: center; }}
            .content {{ padding: 20px; background: #f9f9f9; }}
            .status {{ font-size: 18px; font-weight: bold; color: #1a365d; padding: 15px; background: #e8f4f8; margin: 20px 0; border-left: 4px solid #2563eb; }}
            .notes {{ background: #fff; padding: 15px; border: 1px solid #ddd; margin: 15px 0; }}
            .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
            a {{ color: #2563eb; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>ScholarPress</h1>
            </div>
            <div class="content">
                <h2>Submission Status Update</h2>
                <p>Dear Author,</p>
                
                <p><strong>Title:</strong> {submission.title}</p>
                <p><strong>Tracking ID:</strong> {submission.tracking_id}</p>
                
                <div class="status">
                    {status_message}
                </div>
                
                {"<div class='notes'><strong>Notes from Editor:</strong><br>" + notes + "</div>" if notes else ""}
                
                <p>You can view the full status history of your submission:</p>
                <p><a href="{site_url}/submit/track?tracking_id={submission.tracking_id}">View Submission Status</a></p>
                
                <p>Best regards,<br>The ScholarPress Editorial Team</p>
            </div>
            <div class="footer">
                <p>This is an automated message. Please do not reply directly to this email.</p>
            </div>
        </div>
    </body>
    </html>
    """
    
    send_email(subject, submission.contact_email, body_html)


def send_contact_confirmation(thread, site_url):
    """Send confirmation email when a contact message is received."""
    subject = f"Message Received - {thread.subject}"
    
    conversation_link = f"{site_url}/contact/thread/{thread.secure_token}"
    
    body_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: #1a365d; color: white; padding: 20px; text-align: center; }}
            .content {{ padding: 20px; background: #f9f9f9; }}
            .link-box {{ background: #e8f4f8; padding: 20px; margin: 20px 0; text-align: center; }}
            .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
            a {{ color: #2563eb; }}
            .btn {{ display: inline-block; background: #1a365d; color: white !important; padding: 12px 24px; text-decoration: none; border-radius: 4px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>ScholarPress</h1>
            </div>
            <div class="content">
                <h2>We've Received Your Message</h2>
                <p>Dear {thread.name},</p>
                <p>Thank you for contacting ScholarPress. We have received your message regarding:</p>
                <p><strong>Subject:</strong> {thread.subject}</p>
                
                <p>Our team will review your message and respond as soon as possible.</p>
                
                <div class="link-box">
                    <p><strong>Your Conversation Link</strong></p>
                    <p>Use this link to view responses and continue the conversation:</p>
                    <p><a href="{conversation_link}" class="btn">View Conversation</a></p>
                    <p style="font-size: 12px; color: #666; margin-top: 15px;">
                        Please save this link - it's your unique access to this conversation.
                    </p>
                </div>
                
                <p>Best regards,<br>The ScholarPress Team</p>
            </div>
            <div class="footer">
                <p>This is an automated message. Please do not reply directly to this email.</p>
            </div>
        </div>
    </body>
    </html>
    """
    
    send_email(subject, thread.email, body_html)


def send_contact_reply_notification(thread, message, site_url):
    """Send notification when admin/editor replies to a contact message."""
    subject = f"New Reply - {thread.subject}"
    
    conversation_link = f"{site_url}/contact/thread/{thread.secure_token}"
    
    body_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: #1a365d; color: white; padding: 20px; text-align: center; }}
            .content {{ padding: 20px; background: #f9f9f9; }}
            .message-box {{ background: #fff; padding: 20px; border-left: 4px solid #2563eb; margin: 20px 0; }}
            .footer {{ text-align: center; padding: 20px; color: #666; font-size: 12px; }}
            a {{ color: #2563eb; }}
            .btn {{ display: inline-block; background: #1a365d; color: white !important; padding: 12px 24px; text-decoration: none; border-radius: 4px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>ScholarPress</h1>
            </div>
            <div class="content">
                <h2>New Reply to Your Message</h2>
                <p>Dear {thread.name},</p>
                <p>You have received a new reply regarding: <strong>{thread.subject}</strong></p>
                
                <div class="message-box">
                    {message.message}
                </div>
                
                <p style="text-align: center;">
                    <a href="{conversation_link}" class="btn">View Full Conversation</a>
                </p>
                
                <p>Best regards,<br>The ScholarPress Team</p>
            </div>
            <div class="footer">
                <p>This is an automated message. Please do not reply directly to this email.</p>
            </div>
        </div>
    </body>
    </html>
    """
    
    send_email(subject, thread.email, body_html)
