import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import random
from datetime import datetime, timedelta
from app.config import Config
from app.utils.company_settings import get_company_smtp_settings



class EmailSender:

    def generate_verification_code(self):
        return ''.join([str(random.randint(0, 9)) for _ in range(4)])
    
    def generate_reset_code(self):
        return ''.join([str(random.randint(0, 9)) for _ in range(6)])

    def send_verification_email(self, to_email, company_name, verification_code):
        try:
            msg = MIMEMultipart()
            msg['From'] = f"{Config.SENDER_NAME} <{Config.SENDER_EMAIL}>"
            msg['To'] = to_email
            msg['Subject'] = "Verify Your Company Email"

            html = f"""
            <html>
                <body style="font-family: Arial, sans-serif;">
                    <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                        <h2>Welcome to MyKaptaan!</h2>
                        <p>Dear {company_name},</p>
                        <p>Thank you for registering. Please use the following verification code to complete your registration:</p>
                        <div style="background-color: #f4f4f4; padding: 10px; text-align: center; font-size: 24px; letter-spacing: 5px; margin: 20px 0;">
                            <strong>{verification_code}</strong>
                        </div>
                        <p>This code will expire in 15 minutes.</p>
                        <p>If you didn't request this verification, please ignore this email.</p>
                        <p>Best regards,<br>MyKaptaan Team</p>
                    </div>
                </body>
            </html>
            """

            msg.attach(MIMEText(html, 'html'))

            # Try different SMTP configurations
            try:
                # Method 1: SMTP_SSL (most common)
                with smtplib.SMTP_SSL(Config.SMTP_SERVER, Config.SMTP_PORT) as server:
                    server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
                    server.send_message(msg)
                print("Email sent successfully using SMTP_SSL")
                return True
            except Exception as ssl_error:
                print(f"SMTP_SSL failed: {str(ssl_error)}")
                try:
                    # Method 2: SMTP with STARTTLS
                    with smtplib.SMTP(Config.SMTP_SERVER, 587) as server:
                        server.starttls()
                        server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
                        server.send_message(msg)
                    print("Email sent successfully using SMTP with STARTTLS")
                    return True
                except Exception as tls_error:
                    print(f"SMTP with STARTTLS failed: {str(tls_error)}")
                    try:
                        # Method 3: SMTP without encryption (for some servers)
                        with smtplib.SMTP(Config.SMTP_SERVER, 25) as server:
                            server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
                            server.send_message(msg)
                        print("Email sent successfully using SMTP without encryption")
                        return True
                    except Exception as plain_error:
                        print(f"All SMTP methods failed. Last error: {str(plain_error)}")
                        return False

        except Exception as e:
            print(f"Error sending email: {str(e)}")
            return False

    def send_password_reset_email(self, to_email, company_name, reset_code):
        try:
            msg = MIMEMultipart()
            msg['From'] = f"{Config.SENDER_NAME} <{Config.SENDER_EMAIL}>"
            msg['To'] = to_email
            msg['Subject'] = "Password Reset Request"

            html = f"""
            <html>
                <body style="font-family: Arial, sans-serif;">
                    <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                        <h2>Password Reset Request</h2>
                        <p>Dear {company_name},</p>
                        <p>We received a request to reset your password. Please use the following code to reset your password:</p>
                        <div style="background-color: #f4f4f4; padding: 15px; text-align: center; font-size: 28px; letter-spacing: 5px; margin: 20px 0; border-radius: 5px;">
                            <strong>{reset_code}</strong>
                        </div>
                        <p>This code will expire in 15 minutes.</p>
                        <p>If you didn't request this password reset, please ignore this email and your password will remain unchanged.</p>
                        <p>For security reasons, please do not share this code with anyone.</p>
                        <p>Best regards,<br>MyKaptaan Team</p>
                    </div>
                </body>
            </html>
            """

            msg.attach(MIMEText(html, 'html'))

            # Try different SMTP configurations
            try:
                # Method 1: SMTP_SSL (most common)
                with smtplib.SMTP_SSL(Config.SMTP_SERVER, Config.SMTP_PORT) as server:
                    server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
                    server.send_message(msg)
                print("Password reset email sent successfully using SMTP_SSL")
                return True
            except Exception as ssl_error:
                print(f"SMTP_SSL failed: {str(ssl_error)}")
                try:
                    # Method 2: SMTP with STARTTLS
                    with smtplib.SMTP(Config.SMTP_SERVER, 587) as server:
                        server.starttls()
                        server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
                        server.send_message(msg)
                    print("Password reset email sent successfully using SMTP with STARTTLS")
                    return True
                except Exception as tls_error:
                    print(f"SMTP with STARTTLS failed: {str(tls_error)}")
                    try:
                        # Method 3: SMTP without encryption (for some servers)
                        with smtplib.SMTP(Config.SMTP_SERVER, 25) as server:
                            server.login(Config.SMTP_USER, Config.SMTP_PASSWORD)
                            server.send_message(msg)
                        print("Password reset email sent successfully using SMTP without encryption")
                        return True
                    except Exception as plain_error:
                        print(f"All SMTP methods failed. Last error: {str(plain_error)}")
                        return False

        except Exception as e:
            print(f"Error sending password reset email: {str(e)}")
            return False

def send_simple_email(to_email, subject, body, from_name, from_email, company_id):
    smtp_settings = get_company_smtp_settings(company_id)
    if not smtp_settings:
        print(f"No SMTP settings found for company {company_id}")
        return
    msg = MIMEMultipart()
    msg['From'] = f"{from_name} <{from_email}>"
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    with smtplib.SMTP_SSL(smtp_settings[1], smtp_settings[2], timeout=20) as server:
        server.login(smtp_settings[3], smtp_settings[4])
        server.send_message(msg) 