from flask import current_app, render_template_string
from flask_mail import Message
from app import mail
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def send_contact_notification(contact_message):
    """Send notification to admin when new contact form is submitted"""
    try:
        msg = Message(
            subject=f'New Contact Form Submission: {contact_message.subject}',
            sender=current_app.config['MAIL_DEFAULT_SENDER'],
            recipients=[current_app.config['COMPANY_EMAIL']],
            reply_to=contact_message.email
        )

        msg.body = f"""
New Contact Form Submission

From: {contact_message.name}
Email: {contact_message.email}
Phone: {contact_message.phone or 'Not provided'}
Subject: {contact_message.subject}
Date: {contact_message.created_at.strftime('%Y-%m-%d %H:%M')}

Message:
{contact_message.message}

---
View in admin panel: http://localhost:5000/admin/messages
"""

        msg.html = f"""
        <h2>New Contact Form Submission</h2>
        <table style='border-collapse: collapse; width: 100%;'>
            <tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>From:</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>{contact_message.name}</td></tr>
            <tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>Email:</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>{contact_message.email}</td></tr>
            <tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>Phone:</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>{contact_message.phone or 'Not provided'}</td></tr>
            <tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>Subject:</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>{contact_message.subject}</td></tr>
            <tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>Date:</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>{contact_message.created_at.strftime('%Y-%m-%d %H:%M')}</td></tr>
        </table>
        <h3>Message:</h3>
        <p style='background: #f5f5f5; padding: 15px; border-radius: 5px;'>{contact_message.message}</p>
        <p><a href='http://localhost:5000/admin/messages' style='background: #2563eb; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>View in Admin Panel</a></p>
        """

        mail.send(msg)
        logger.info(f"Contact notification sent for message ID: {contact_message.id}")
        return True
    except Exception as e:
        logger.error(f"Failed to send contact notification: {str(e)}")
        return False

def send_reply_to_contact(contact_message, admin_user):
    """Send admin reply to the original sender"""
    try:
        msg = Message(
            subject=f'Re: {contact_message.subject} - A+ Academy',
            sender=current_app.config['MAIL_DEFAULT_SENDER'],
            recipients=[contact_message.email],
            reply_to=current_app.config['COMPANY_EMAIL']
        )

        msg.body = f"""
Dear {contact_message.name},

Thank you for contacting A+ Academy. We have received your message regarding "{contact_message.subject}".

Our Response:
{contact_message.reply_message}

If you have any further questions, please don't hesitate to contact us again.

Best regards,
{admin_user.username}
A+ Academy Team
{current_app.config['COMPANY_PHONE']}
{current_app.config['COMPANY_EMAIL']}

---
Your Original Message:
{contact_message.message}
"""

        msg.html = f"""
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
            <div style='background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0;'>
                <h1 style='margin: 0; font-size: 24px;'>A+ Academy</h1>
                <p style='margin: 10px 0 0 0; opacity: 0.9;'>Excellence in Education</p>
            </div>
            <div style='background: #f8fafc; padding: 30px; border: 1px solid #e2e8f0; border-top: none;'>
                <p style='color: #1e293b; font-size: 16px;'>Dear <strong>{contact_message.name}</strong>,</p>
                <p style='color: #475569; line-height: 1.6;'>Thank you for contacting A+ Academy. We have received your message regarding "<strong>{contact_message.subject}</strong>".</p>

                <div style='background: white; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #2563eb; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>
                    <h3 style='color: #2563eb; margin-top: 0;'>Our Response:</h3>
                    <p style='color: #334155; line-height: 1.6; white-space: pre-wrap;'>{contact_message.reply_message}</p>
                </div>

                <p style='color: #475569;'>If you have any further questions, please don't hesitate to contact us again.</p>

                <div style='margin-top: 30px; padding-top: 20px; border-top: 1px solid #e2e8f0;'>
                    <p style='color: #1e293b; margin: 0;'><strong>Best regards,</strong></p>
                    <p style='color: #2563eb; margin: 5px 0; font-weight: 600;'>{admin_user.username}</p>
                    <p style='color: #64748b; margin: 0; font-size: 14px;'>A+ Academy Team</p>
                    <p style='color: #64748b; margin: 5px 0 0 0; font-size: 14px;'>{current_app.config['COMPANY_PHONE']}</p>
                </div>
            </div>
            <div style='background: #1e293b; color: #94a3b8; padding: 20px; text-align: center; border-radius: 0 0 10px 10px; font-size: 12px;'>
                <p style='margin: 0;'>© 2024 A+ Academy. All rights reserved.</p>
                <p style='margin: 5px 0 0 0;'>{current_app.config['COMPANY_ADDRESS']}</p>
            </div>
        </div>
        """

        mail.send(msg)
        logger.info(f"Reply sent to {contact_message.email} for message ID: {contact_message.id}")
        return True
    except Exception as e:
        logger.error(f"Failed to send reply: {str(e)}")
        return False
