import smtplib
import asyncio
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from jinja2 import Template
from config import settings
from typing import List

class EmailService:
    def __init__(self):
        self.smtp_server = settings.SMTP_SERVER
        self.smtp_port = settings.SMTP_PORT
        self.username = settings.SMTP_USERNAME
        self.password = settings.SMTP_PASSWORD
        self.from_email = settings.FROM_EMAIL

    async def send_email(self, to_emails: List[str], subject: str, html_content: str, text_content: str = None):
        """Send email using SMTP"""
        try:
            # Create message
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = self.from_email
            msg['To'] = ', '.join(to_emails)

            # Add text content
            if text_content:
                text_part = MIMEText(text_content, 'plain')
                msg.attach(text_part)

            # Add HTML content
            html_part = MIMEText(html_content, 'html')
            msg.attach(html_part)

            # Send email
            server = smtplib.SMTP(self.smtp_server, self.smtp_port)
            server.starttls()
            server.login(self.username, self.password)
            
            for email in to_emails:
                server.sendmail(self.from_email, email, msg.as_string())
            
            server.quit()
            return True
        except Exception as e:
            print(f"Email sending failed: {str(e)}")
            return False

    async def send_otp_email(self, email: str, otp_code: str, purpose: str = "login"):
        """Send OTP email"""
        if purpose == "login":
            subject = "Your Login OTP - Photo Gallery"
            template = """
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f4f4f4; }
                    .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                    .header { text-align: center; margin-bottom: 30px; }
                    .otp-code { font-size: 32px; font-weight: bold; color: #4CAF50; text-align: center; padding: 20px; background: #f8f9fa; border-radius: 8px; margin: 20px 0; letter-spacing: 5px; }
                    .footer { text-align: center; margin-top: 30px; color: #666; font-size: 14px; }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h1 style="color: #333; margin: 0;">Photo Gallery</h1>
                        <p style="color: #666; margin: 10px 0 0 0;">Your Login Verification Code</p>
                    </div>
                    
                    <p>Hello,</p>
                    <p>You have requested to login to your Photo Gallery account. Please use the following OTP code to complete your login:</p>
                    
                    <div class="otp-code">{{ otp_code }}</div>
                    
                    <p style="color: #666; font-size: 14px;">This code will expire in 10 minutes. If you didn't request this login, please ignore this email.</p>
                    
                    <div class="footer">
                        <p>Thank you for using Photo Gallery!</p>
                    </div>
                </div>
            </body>
            </html>
            """
        else:  # password_reset
            subject = "Password Reset OTP - Photo Gallery"
            template = """
            <!DOCTYPE html>
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f4f4f4; }
                    .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                    .header { text-align: center; margin-bottom: 30px; }
                    .otp-code { font-size: 32px; font-weight: bold; color: #FF6B6B; text-align: center; padding: 20px; background: #f8f9fa; border-radius: 8px; margin: 20px 0; letter-spacing: 5px; }
                    .footer { text-align: center; margin-top: 30px; color: #666; font-size: 14px; }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <h1 style="color: #333; margin: 0;">Photo Gallery</h1>
                        <p style="color: #666; margin: 10px 0 0 0;">Password Reset Verification</p>
                    </div>
                    
                    <p>Hello,</p>
                    <p>You have requested to reset your password. Please use the following OTP code to proceed with password reset:</p>
                    
                    <div class="otp-code">{{ otp_code }}</div>
                    
                    <p style="color: #666; font-size: 14px;">This code will expire in 10 minutes. If you didn't request this password reset, please ignore this email and ensure your account is secure.</p>
                    
                    <div class="footer">
                        <p>Thank you for using Photo Gallery!</p>
                    </div>
                </div>
            </body>
            </html>
            """

        # Render template
        template_obj = Template(template)
        html_content = template_obj.render(otp_code=otp_code)
        
        text_content = f"Your Photo Gallery OTP code is: {otp_code}. This code will expire in 10 minutes."

        return await self.send_email([email], subject, html_content, text_content)

# Global email service instance
email_service = EmailService()
