import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from models.user_model import get_user_token, get_latest_event

SMTP_HOST = os.getenv("SMTP_HOST", "mail.imtma.in")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
SMTP_USER = os.getenv("SMTP_USER", "info@imtma.in")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD", "Imtma@123$")
SENDER_EMAIL = os.getenv("SENDER_EMAIL", SMTP_USER)


def send_email_to_user(user_email, user_id, user_face_image, header_image_url):
    """Send clean email with button redirect to gallery."""
    if not user_email:
        raise ValueError("User email is required.")

    # Fetch token from database
    access_token = get_user_token(user_id)
    if not access_token:
        raise Exception("Access token not found for user")

    # ✅ Get event name from database for the From display name
    try:
        event = get_latest_event()
        event_name = event["event_name"] if event and event.get("event_name") else "IMTMA Event"
    except Exception:
        event_name = "IMTMA Event"

    gallery_link = f"http://localhost/event_gallery_system/view.php?token={access_token}"

    msg = MIMEMultipart("alternative")
    msg["Subject"] = "📸 Your Event Photos Are Ready"
    msg["From"] = f"{event_name} <{SENDER_EMAIL}>"  # ✅ Shows event name in inbox
    msg["To"] = user_email

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Your Event Photos</title>
    </head>
    <body style="margin:0; padding:0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">

        <!-- Main Container -->
        <table cellpadding="0" cellspacing="0" border="0" width="100%" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <tr>
                <td align="center" style="padding: 40px 20px;">

                    <!-- Email Card -->
                    <table cellpadding="0" cellspacing="0" border="0" width="100%" style="max-width: 550px; background: #ffffff; border-radius: 24px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); overflow: hidden;">

                        <!-- Header Banner -->
                        <tr>
                            <td style="padding: 0;">
                                <div style="position: relative;">
                                    <img src="{header_image_url}" alt="Event Header" style="width: 100%; height: auto; display: block;">
                                    <div style="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(to top, rgba(0,0,0,0.7), transparent); padding: 40px 20px 20px;"></div>
                                </div>
                            </td>
                        </tr>

                        <!-- Content Section -->
                        <tr>
                            <td style="padding: 40px 30px 30px;">

                                <!-- Badge -->
                                <div style="text-align: center; margin-bottom: 20px;">
                                    <span style="display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 8px 20px; border-radius: 50px; font-size: 14px; font-weight: 600; letter-spacing: 0.5px;">
                                        ✨ NEW PHOTOS AVAILABLE ✨
                                    </span>
                                </div>

                                <!-- Title -->
                                <h1 style="text-align: center; color: #2d3748; font-size: 32px; font-weight: 800; margin: 0 0 10px 0; letter-spacing: -0.5px;">
                                    Your Photos Are Ready!
                                </h1>

                                <!-- Subtitle -->
                                <p style="text-align: center; color: #718096; font-size: 16px; margin-bottom: 30px;">
                                    We've captured your special moments
                                </p>

                                <!-- Divider -->
                                <div style="width: 60px; height: 3px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0 auto 30px; border-radius: 2px;"></div>

                                <!-- User Photo Frame -->
                                <div style="text-align: center; margin-bottom: 30px;">
                                    <div style="display: inline-block; padding: 8px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 20px; box-shadow: 0 10px 30px rgba(102,126,234,0.3);">
                                        <div style="background: white; border-radius: 12px; padding: 4px;">
                                            <img src="{user_face_image}" alt="Your Photo" style="width: 180px; height: 180px; object-fit: cover; border-radius: 12px; display: block;">
                                        </div>
                                    </div>
                                </div>

                                <!-- Message -->
                                <p style="color: #4a5568; font-size: 16px; line-height: 1.6; text-align: center; margin-bottom: 30px;">
                                    We found beautiful photos of you at the event!<br>
                                    Click the button below to view and download your gallery.
                                </p>

                                <!-- CTA Button -->
                                <div style="text-align: center; margin-bottom: 30px;">
                                    <a href="{gallery_link}" style="display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-decoration: none; padding: 16px 42px; border-radius: 50px; font-weight: 700; font-size: 16px; letter-spacing: 0.5px; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(102,126,234,0.4);">
                                        🎬 View My Gallery
                                    </a>
                                </div>

                                <!-- Feature Icons -->
                                <div style="border-top: 1px solid #e2e8f0; padding-top: 25px; margin-top: 10px;">
                                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
                                        <tr>
                                            <td align="center" style="padding: 0 10px;">
                                                <div style="text-align: center;">
                                                    <div style="font-size: 24px; margin-bottom: 8px;">📸</div>
                                                    <div style="color: #718096; font-size: 12px; font-weight: 500;">High Quality</div>
                                                </div>
                                            </td>
                                            <td align="center" style="padding: 0 10px;">
                                                <div style="text-align: center;">
                                                    <div style="font-size: 24px; margin-bottom: 8px;">⬇️</div>
                                                    <div style="color: #718096; font-size: 12px; font-weight: 500;">Easy Download</div>
                                                </div>
                                            </td>
                                            <td align="center" style="padding: 0 10px;">
                                                <div style="text-align: center;">
                                                    <div style="font-size: 24px; margin-bottom: 8px;">🔒</div>
                                                    <div style="color: #718096; font-size: 12px; font-weight: 500;">Private Link</div>
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>

                            </td>
                        </tr>

                        <!-- Footer -->
                        <tr>
                            <td style="background: #f7fafc; padding: 25px 30px; text-align: center; border-top: 1px solid #e2e8f0;">
                                <p style="color: #a0aec0; font-size: 12px; margin: 0 0 10px 0; line-height: 1.5;">
                                    This link is uniquely generated for you and will expire for security.
                                </p>
                                <p style="color: #cbd5e0; font-size: 11px; margin: 0;">
                                    Powered by <strong style="color: #a0aec0;">AI Event Photo System</strong>
                                </p>
                                <p style="color: #cbd5e0; font-size: 11px; margin: 10px 0 0 0;">
                                    © 2024 {event_name}. All rights reserved.
                                </p>
                            </td>
                        </tr>

                    </table>

                </td>
            </tr>
        </table>

    </body>
    </html>
    """

    msg.attach(MIMEText(html_content, "html"))

    server = smtplib.SMTP(SMTP_HOST, SMTP_PORT)
    try:
        server.starttls()
        server.login(SMTP_USER, SMTP_PASSWORD)
        server.sendmail(SENDER_EMAIL, user_email, msg.as_string())
    finally:
        server.quit()