import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import logging
from typing import Optional
import os


class EmailSender:
    """Email sending service using SMTP"""
    
    def __init__(self, 
                 host: str = "smtp.gmail.com",
                 port: int = 465,
                 username: str = None,
                 password: str = None,
                 encryption: str = "ssl",
                 from_address: str = None,
                 from_name: str = "Troy Rides"):
        """
        Initialize email sender
        
        Args:
            host: SMTP server host
            port: SMTP server port
            username: SMTP username/email
            password: SMTP password (app password for Gmail)
            encryption: Encryption type (ssl or tls)
            from_address: From email address
            from_name: From name
        """
        self.host = host
        self.port = port
        self.username = username or os.getenv("MAIL_USERNAME")
        self.password = password or os.getenv("MAIL_PASSWORD")
        self.encryption = encryption.lower()
        self.from_address = from_address or os.getenv("MAIL_FROM_ADDRESS") or self.username
        self.from_name = from_name or os.getenv("MAIL_FROM_NAME", "Troy Rides")
        self.logger = logging.getLogger(__name__)
        
        if not self.username or not self.password:
            self.logger.warning("SMTP credentials not configured")
    
    def create_fare_estimate_email(self, recipient_email: str, estimate_fare: str, payment_link: str, 
                                   customer_name: Optional[str] = None) -> MIMEMultipart:
        """
        Create email template for fare estimate
        
        Args:
            recipient_email: Recipient email address
            estimate_fare: Estimated fare amount
            payment_link: Payment link URL
            customer_name: Optional customer name
            
        Returns:
            MIMEMultipart email message
        """
        # Create message
        msg = MIMEMultipart('alternative')
        msg['From'] = f"{self.from_name} <{self.from_address}>"
        msg['To'] = recipient_email
        msg['Subject'] = "Your Ride Fare Estimate - Troy Rides"
        
        # Customer name or generic greeting
        greeting = f"Hello {customer_name}," if customer_name else "Hello,"
        
        # HTML email template
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body {{
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                }}
                .container {{
                    background-color: #f9f9f9;
                    border-radius: 10px;
                    padding: 30px;
                    margin: 20px 0;
                }}
                .header {{
                    background-color: #2c3e50;
                    color: white;
                    padding: 20px;
                    border-radius: 10px 10px 0 0;
                    text-align: center;
                }}
                .header h1 {{
                    margin: 0;
                    font-size: 24px;
                }}
                .content {{
                    background-color: white;
                    padding: 30px;
                    border-radius: 0 0 10px 10px;
                }}
                .fare-box {{
                    background-color: #3498db;
                    color: white;
                    padding: 20px;
                    border-radius: 8px;
                    text-align: center;
                    margin: 20px 0;
                }}
                .fare-amount {{
                    font-size: 36px;
                    font-weight: bold;
                    margin: 10px 0;
                }}
                .payment-button {{
                    display: inline-block;
                    background-color: #27ae60;
                    color: white;
                    padding: 15px 30px;
                    text-decoration: none;
                    border-radius: 5px;
                    font-weight: bold;
                    margin: 20px 0;
                    font-size: 16px;
                }}
                .payment-button:hover {{
                    background-color: #229954;
                }}
                .footer {{
                    text-align: center;
                    margin-top: 30px;
                    padding-top: 20px;
                    border-top: 1px solid #ddd;
                    color: #777;
                    font-size: 12px;
                }}
                .info-box {{
                    background-color: #ecf0f1;
                    padding: 15px;
                    border-radius: 5px;
                    margin: 20px 0;
                    border-left: 4px solid #3498db;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>🚗 Troy Rides</h1>
                </div>
                <div class="content">
                    <p>{greeting}</p>
                    
                    <p>Thank you for choosing Troy Rides! We're excited to provide you with transportation services.</p>
                    
                    <div class="fare-box">
                        <p style="margin: 0 0 10px 0; font-size: 14px;">Estimated Fare</p>
                        <div class="fare-amount">${estimate_fare}</div>
                    </div>
                    
                    <p>Please review your fare estimate above. To proceed with your booking, please complete the payment using the link below:</p>
                    
                    <div style="text-align: center;">
                        <a href="{payment_link}" class="payment-button">💳 Pay Now</a>
                    </div>
                    
                    <div class="info-box">
                        <p style="margin: 0;"><strong>Payment Link:</strong></p>
                        <p style="margin: 5px 0 0 0; word-break: break-all;">
                            <a href="{payment_link}" style="color: #3498db;">{payment_link}</a>
                        </p>
                    </div>
                    
                    <p>If you have any questions or need assistance, please don't hesitate to contact us.</p>
                    
                    <p>Best regards,<br>
                    <strong>Troy Rides Team</strong></p>
                </div>
                <div class="footer">
                    <p>This is an automated email. Please do not reply to this message.</p>
                    <p>&copy; {self.from_name}. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        # Plain text version
        text_content = f"""
        Troy Rides - Fare Estimate
        
        {greeting}
        
        Thank you for choosing Troy Rides! We're excited to provide you with transportation services.
        
        Estimated Fare: ${estimate_fare}
        
        To proceed with your booking, please complete the payment using the link below:
        
        {payment_link}
        
        If you have any questions or need assistance, please don't hesitate to contact us.
        
        Best regards,
        Troy Rides Team
        
        ---
        This is an automated email. Please do not reply to this message.
        """
        
        # Attach both versions
        part1 = MIMEText(text_content, 'plain')
        part2 = MIMEText(html_content, 'html')
        
        msg.attach(part1)
        msg.attach(part2)
        
        return msg
    
    def send_email(self, recipient_email: str, subject: str, html_content: str, 
                   text_content: Optional[str] = None) -> bool:
        """
        Send email using SMTP
        
        Args:
            recipient_email: Recipient email address
            subject: Email subject
            html_content: HTML email content
            text_content: Plain text email content (optional)
            
        Returns:
            True if successful, False otherwise
        """
        try:
            # Create message
            msg = MIMEMultipart('alternative')
            msg['From'] = f"{self.from_name} <{self.from_address}>"
            msg['To'] = recipient_email
            msg['Subject'] = subject
            
            # Attach content
            if text_content:
                part1 = MIMEText(text_content, 'plain')
                msg.attach(part1)
            
            part2 = MIMEText(html_content, 'html')
            msg.attach(part2)
            
            # Send email
            return self._send_smtp(msg, recipient_email)
            
        except Exception as e:
            self.logger.error(f"Error sending email: {e}", exc_info=True)
            return False
    
    def create_driver_info_email(self, recipient_email: str, driver_name: str, driver_email: str, 
                                 driver_phone: str, otp: str) -> MIMEMultipart:
        """
        Create email template for driver information with OTP
        
        Args:
            recipient_email: Recipient email address
            driver_name: Driver name
            driver_email: Driver email address
            driver_phone: Driver phone number
            otp: One-time password/OTP
            
        Returns:
            MIMEMultipart email message
        """
        # Create message
        msg = MIMEMultipart('alternative')
        msg['From'] = f"{self.from_name} <{self.from_address}>"
        msg['To'] = recipient_email
        msg['Subject'] = "Your Driver Information - Troy Rides"
        
        # HTML email template
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body {{
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                }}
                .container {{
                    background-color: #f9f9f9;
                    border-radius: 10px;
                    padding: 30px;
                    margin: 20px 0;
                }}
                .header {{
                    background-color: #2c3e50;
                    color: white;
                    padding: 20px;
                    border-radius: 10px 10px 0 0;
                    text-align: center;
                }}
                .header h1 {{
                    margin: 0;
                    font-size: 24px;
                }}
                .content {{
                    background-color: white;
                    padding: 30px;
                    border-radius: 0 0 10px 10px;
                }}
                .driver-info-box {{
                    background-color: #ecf0f1;
                    padding: 20px;
                    border-radius: 8px;
                    margin: 20px 0;
                    border-left: 4px solid #3498db;
                }}
                .driver-info-item {{
                    margin: 10px 0;
                    padding: 10px;
                    background-color: white;
                    border-radius: 5px;
                }}
                .driver-info-label {{
                    font-weight: bold;
                    color: #2c3e50;
                    display: inline-block;
                    width: 120px;
                }}
                .driver-info-value {{
                    color: #333;
                }}
                .otp-box {{
                    background-color: #3498db;
                    color: white;
                    padding: 25px;
                    border-radius: 8px;
                    text-align: center;
                    margin: 25px 0;
                }}
                .otp-label {{
                    font-size: 14px;
                    margin-bottom: 10px;
                    opacity: 0.9;
                }}
                .otp-code {{
                    font-size: 42px;
                    font-weight: bold;
                    letter-spacing: 8px;
                    margin: 15px 0;
                    font-family: 'Courier New', monospace;
                }}
                .info-note {{
                    background-color: #fff3cd;
                    border-left: 4px solid #ffc107;
                    padding: 15px;
                    border-radius: 5px;
                    margin: 20px 0;
                    color: #856404;
                }}
                .footer {{
                    text-align: center;
                    margin-top: 30px;
                    padding-top: 20px;
                    border-top: 1px solid #ddd;
                    color: #777;
                    font-size: 12px;
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>🚗 Troy Rides</h1>
                </div>
                <div class="content">
                    <p>Hello,</p>
                    
                    <p>Your ride has been assigned! Here are your driver details:</p>
                    
                    <div class="driver-info-box">
                        <h3 style="margin-top: 0; color: #2c3e50;">Driver Information</h3>
                        
                        <div class="driver-info-item">
                            <span class="driver-info-label">Name:</span>
                            <span class="driver-info-value">{driver_name}</span>
                        </div>
                        
                        <div class="driver-info-item">
                            <span class="driver-info-label">Email:</span>
                            <span class="driver-info-value">{driver_email}</span>
                        </div>
                        
                        <div class="driver-info-item">
                            <span class="driver-info-label">Phone:</span>
                            <span class="driver-info-value">{driver_phone}</span>
                        </div>
                    </div>
                    
                    <div class="otp-box">
                        <div class="otp-label">Your One-Time Password (OTP)</div>
                        <div class="otp-code">{otp}</div>
                        <div style="font-size: 12px; margin-top: 10px; opacity: 0.9;">
                            Please provide this OTP to your driver to verify your ride
                        </div>
                    </div>
                    
                    <div class="info-note">
                        <strong>⚠️ Important:</strong> Please keep your OTP confidential and only share it with your assigned driver when they arrive.
                    </div>
                    
                    <p>Your driver will contact you shortly. If you have any questions or concerns, please don't hesitate to contact us.</p>
                    
                    <p>Best regards,<br>
                    <strong>Troy Rides Team</strong></p>
                </div>
                <div class="footer">
                    <p>This is an automated email. Please do not reply to this message.</p>
                    <p>&copy; {self.from_name}. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        # Plain text version
        text_content = f"""
        Troy Rides - Driver Information
        
        Hello,
        
        Your ride has been assigned! Here are your driver details:
        
        Driver Information:
        -------------------
        Name: {driver_name}
        Email: {driver_email}
        Phone: {driver_phone}
        
        Your One-Time Password (OTP): {otp}
        
        Please provide this OTP to your driver to verify your ride.
        
        Important: Please keep your OTP confidential and only share it with your assigned driver when they arrive.
        
        Your driver will contact you shortly. If you have any questions or concerns, please don't hesitate to contact us.
        
        Best regards,
        Troy Rides Team
        
        ---
        This is an automated email. Please do not reply to this message.
        """
        
        # Attach both versions
        part1 = MIMEText(text_content, 'plain')
        part2 = MIMEText(html_content, 'html')
        
        msg.attach(part1)
        msg.attach(part2)
        
        return msg
    
    def send_fare_estimate(self, recipient_email: str, estimate_fare: str, payment_link: str,
                          customer_name: Optional[str] = None) -> bool:
        """
        Send fare estimate email
        
        Args:
            recipient_email: Recipient email address
            estimate_fare: Estimated fare amount
            payment_link: Payment link URL
            customer_name: Optional customer name
            
        Returns:
            True if successful, False otherwise
        """
        try:
            msg = self.create_fare_estimate_email(recipient_email, estimate_fare, payment_link, customer_name)
            return self._send_smtp(msg, recipient_email)
        except Exception as e:
            self.logger.error(f"Error sending fare estimate email: {e}", exc_info=True)
            return False
    
    def send_driver_info(self, recipient_email: str, driver_name: str, driver_email: str,
                        driver_phone: str, otp: str) -> bool:
        """
        Send driver information email with OTP
        
        Args:
            recipient_email: Recipient email address
            driver_name: Driver name
            driver_email: Driver email address
            driver_phone: Driver phone number
            otp: One-time password/OTP
            
        Returns:
            True if successful, False otherwise
        """
        try:
            msg = self.create_driver_info_email(recipient_email, driver_name, driver_email, driver_phone, otp)
            return self._send_smtp(msg, recipient_email)
        except Exception as e:
            self.logger.error(f"Error sending driver info email: {e}", exc_info=True)
            return False
    
    def _send_smtp(self, msg: MIMEMultipart, recipient_email: str) -> bool:
        """
        Send email via SMTP
        
        Args:
            msg: Email message
            recipient_email: Recipient email address
            
        Returns:
            True if successful, False otherwise
        """
        try:
            if self.encryption == "ssl":
                # SSL connection
                server = smtplib.SMTP_SSL(self.host, self.port)
            else:
                # TLS connection
                server = smtplib.SMTP(self.host, self.port)
                server.starttls()
            
            # Login
            server.login(self.username, self.password)
            
            # Send email
            text = msg.as_string()
            server.sendmail(self.from_address, recipient_email, text)
            server.quit()
            
            self.logger.info(f"Email sent successfully to {recipient_email}")
            return True
            
        except smtplib.SMTPAuthenticationError as e:
            self.logger.error(f"SMTP Authentication failed: {e}")
            return False
        except smtplib.SMTPException as e:
            self.logger.error(f"SMTP error: {e}")
            return False
        except Exception as e:
            self.logger.error(f"Error sending email via SMTP: {e}", exc_info=True)
            return False
