from django.core.mail import send_mail, EmailMultiAlternatives, get_connection
from django.template.loader import render_to_string
from django.conf import settings
from django.utils.html import strip_tags


def send_welcome_email(user, verification_token=None):
    """Send welcome email after registration"""
    subject = f"Welcome to Wananchimart, {user.full_name}!"

    # Build verification URL if token provided
    verify_url = None
    if verification_token and user.email:
        verify_url = f"{settings.FRONTEND_URL}/verify-email?token={verification_token.token}"

    context = {
        'user': user,
        'verify_url': verify_url,
        'frontend_url': settings.FRONTEND_URL,
    }

    # HTML message
    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #f97316; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            h1 {{ margin: 0; font-size: 28px; }}
            .highlight {{ color: #f97316; font-weight: bold; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Welcome to Wananchimart!</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>Thank you for joining <span class="highlight">Wananchimart</span>! We're excited to have you on board.</p>

                {"<p>You've registered as a <strong>" + user.get_user_type_display() + "</strong>.</p>" if user.user_type else ""}

                {f'''
                <p>Please verify your email address by clicking the button below:</p>
                <p style="text-align: center;">
                    <a href="{verify_url}" class="button">Verify Email Address</a>
                </p>
                <p><small>If the button doesn't work, copy and paste this link into your browser:</small></p>
                <p><small>{verify_url}</small></p>
                ''' if verify_url else '''
                <p>You can now start exploring the marketplace!</p>
                '''}

                <p>If you have any questions, feel free to reach out to our support team.</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = strip_tags(html_message)

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send welcome email: {e}")
        return False

    return False


def send_otp_email(user, otp):
    """Send OTP via email for login verification"""
    subject = "Your Wananchimart Login Code"

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .otp-box {{ background: white; border: 2px dashed #f97316; padding: 20px; text-align: center; margin: 20px 0; border-radius: 10px; }}
            .otp-code {{ font-size: 36px; font-weight: bold; letter-spacing: 8px; color: #f97316; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .warning {{ background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0; }}
            h1 {{ margin: 0; font-size: 24px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Your Login Code</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>You requested to log in to your Wananchimart account. Use the code below to complete your login:</p>

                <div class="otp-box">
                    <div class="otp-code">{otp.otp_code}</div>
                </div>

                <div class="warning">
                    <strong>Important:</strong> This code expires in 10 minutes. Do not share this code with anyone.
                </div>

                <p>If you didn't request this code, please ignore this email or contact support if you're concerned about your account security.</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Your Wananchimart login code is: {otp.otp_code}

    This code expires in 10 minutes. Do not share this code with anyone.

    If you didn't request this code, please ignore this email.

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send OTP email: {e}")
        return False

    return False


def send_password_reset_otp_email(user, otp):
    """Send OTP via email for password reset"""
    subject = "Your Wananchimart Password Reset Code"

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .otp-box {{ background: white; border: 2px dashed #f97316; padding: 20px; text-align: center; margin: 20px 0; border-radius: 10px; }}
            .otp-code {{ font-size: 36px; font-weight: bold; letter-spacing: 8px; color: #f97316; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .warning {{ background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0; }}
            h1 {{ margin: 0; font-size: 24px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Password Reset Code</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>You requested to reset your password. Use the code below to proceed:</p>

                <div class="otp-box">
                    <div class="otp-code">{otp.otp_code}</div>
                </div>

                <div class="warning">
                    <strong>Important:</strong> This code expires in 10 minutes. Do not share this code with anyone.
                </div>

                <p>If you didn't request a password reset, please ignore this email. Your password will remain unchanged.</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Your Wananchimart password reset code is: {otp.otp_code}

    This code expires in 10 minutes. Do not share this code with anyone.

    If you didn't request this, please ignore this email.

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send password reset OTP email: {e}")
        return False

    return False


def send_email_verification(user, token):
    """Send email verification link"""
    subject = "Verify Your Wananchimart Email"
    verify_url = f"{settings.FRONTEND_URL}/verify-email?token={token.token}"

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #f97316; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            h1 {{ margin: 0; font-size: 24px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Verify Your Email</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>Please click the button below to verify your email address:</p>

                <p style="text-align: center;">
                    <a href="{verify_url}" class="button">Verify Email Address</a>
                </p>

                <p><small>If the button doesn't work, copy and paste this link:</small></p>
                <p><small>{verify_url}</small></p>

                <p>This link expires in 24 hours.</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Please verify your email by visiting: {verify_url}

    This link expires in 24 hours.

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send verification email: {e}")
        return False

    return False


def send_upgrade_email(user, vendor_profile, amount, plan_type='monthly', expires_at=None):
    """Send email after successful Pro upgrade"""
    subject = "Welcome to Wananchimart Pro!"

    plan_label = "Yearly Plan" if plan_type == 'yearly' else "Monthly Plan"
    expiry_str = expires_at.strftime('%B %d, %Y') if expires_at else 'N/A'

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f59e0b 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #f59e0b; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .feature-list {{ background: white; padding: 20px; border-radius: 10px; margin: 20px 0; }}
            .feature-item {{ padding: 8px 0; border-bottom: 1px solid #eee; }}
            .feature-item:last-child {{ border-bottom: none; }}
            .crown {{ font-size: 48px; }}
            h1 {{ margin: 0; font-size: 28px; }}
            .highlight {{ color: #f59e0b; font-weight: bold; }}
            .amount {{ font-size: 24px; font-weight: bold; color: #f59e0b; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="crown">&#128081;</div>
                <h1>Welcome to Pro!</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>Congratulations! Your <span class="highlight">Wananchimart Pro</span> subscription is now active for <strong>{vendor_profile.shop_name}</strong>.</p>

                <p>Plan: <strong>{plan_label}</strong></p>
                <p>Amount paid: <span class="amount">KES {amount:,.2f}</span></p>
                <p>Valid until: <strong>{expiry_str}</strong></p>

                <div class="feature-list">
                    <h3>Your Pro Features:</h3>
                    <div class="feature-item">&#10004; Up to 100 products</div>
                    <div class="feature-item">&#10004; 5 images per product</div>
                    <div class="feature-item">&#10004; Video uploads</div>
                    <div class="feature-item">&#10004; Discount pricing</div>
                    <div class="feature-item">&#10004; Featured products</div>
                    <div class="feature-item">&#10004; Analytics dashboard</div>
                    <div class="feature-item">&#10004; Priority in search</div>
                    <div class="feature-item">&#10004; Direct messaging</div>
                </div>

                <p>You can manage your subscription and renew from the "My Plan" page in your dashboard.</p>

                <p style="text-align: center;">
                    <a href="{settings.FRONTEND_URL}/vendor/plan" class="button">View My Plan</a>
                </p>

                <p>Thank you for upgrading and supporting Wananchimart!</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Congratulations! Your Wananchimart Pro subscription is now active for {vendor_profile.shop_name}.

    Plan: {plan_label}
    Amount paid: KES {amount:,.2f}
    Valid until: {expiry_str}

    Your Pro Features:
    - Up to 100 products
    - 5 images per product
    - Video uploads
    - Discount pricing
    - Featured products
    - Analytics dashboard
    - Priority in search
    - Direct messaging

    You can manage your subscription from the "My Plan" page in your dashboard.

    Thank you for upgrading!

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send upgrade email: {e}")
        return False

    return False


def send_verification_submitted_email(user, vendor_profile):
    """Send email when verification request is submitted"""
    subject = "Verification Request Received - Wananchimart"

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #3b82f6; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .info-box {{ background: #eff6ff; border-left: 4px solid #3b82f6; padding: 15px; margin: 20px 0; border-radius: 0 8px 8px 0; }}
            h1 {{ margin: 0; font-size: 24px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Verification Request Received</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>We've received your verification request for <strong>{vendor_profile.shop_name}</strong>. Our team will review your submission and get back to you.</p>

                <div class="info-box">
                    <strong>What happens next?</strong>
                    <p style="margin: 5px 0 0;">Our team will review your business information and verify your account. You'll receive a notification once the review is complete.</p>
                </div>

                <p style="text-align: center;">
                    <a href="{settings.FRONTEND_URL}/vendor/verify" class="button">Check Status</a>
                </p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    We've received your verification request for {vendor_profile.shop_name}. Our team will review your submission and get back to you.

    You can check the status at: {settings.FRONTEND_URL}/vendor/verify

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send verification submitted email: {e}")
        return False

    return False


def send_verification_approved_email(user, vendor_profile):
    """Send email when verification is approved"""
    subject = "You're Verified! - Wananchimart"

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #10b981; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .badge-icon {{ font-size: 48px; }}
            h1 {{ margin: 0; font-size: 28px; }}
            .highlight {{ color: #10b981; font-weight: bold; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="badge-icon">&#9989;</div>
                <h1>You're Verified!</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>Congratulations! Your business <span class="highlight">{vendor_profile.shop_name}</span> has been verified on Wananchimart.</p>

                <p>A verified badge is now displayed on your profile and shop, helping you build trust with customers.</p>

                <p style="text-align: center;">
                    <a href="{settings.FRONTEND_URL}/vendor" class="button">Go to Dashboard</a>
                </p>

                <p>Thank you for being part of Wananchimart!</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Congratulations! Your business {vendor_profile.shop_name} has been verified on Wananchimart.

    A verified badge is now displayed on your profile and shop.

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send verification approved email: {e}")
        return False

    return False


def send_sponsored_ad_email(user, vendor_profile, item_name, item_type, days, amount, starts_at, ends_at):
    """Send email after successful sponsored ad purchase"""
    subject = "Sponsored Ad Confirmed - Wananchimart"

    start_str = starts_at.strftime('%B %d, %Y') if starts_at else 'N/A'
    end_str = ends_at.strftime('%B %d, %Y') if ends_at else 'N/A'
    type_label = item_type.capitalize()

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f59e0b 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #f59e0b; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .details {{ background: white; padding: 20px; border-radius: 10px; margin: 20px 0; }}
            .detail-row {{ padding: 8px 0; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; }}
            .detail-row:last-child {{ border-bottom: none; }}
            h1 {{ margin: 0; font-size: 28px; }}
            .highlight {{ color: #f59e0b; font-weight: bold; }}
            .amount {{ font-size: 24px; font-weight: bold; color: #f59e0b; }}
            .megaphone {{ font-size: 48px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="megaphone">&#128226;</div>
                <h1>Ad Confirmed!</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>Your sponsored ad for <span class="highlight">{item_name}</span> is now live on Wananchimart!</p>

                <div class="details">
                    <h3>Ad Details</h3>
                    <div class="detail-row"><span>Item:</span> <strong>{item_name}</strong></div>
                    <div class="detail-row"><span>Type:</span> <strong>{type_label}</strong></div>
                    <div class="detail-row"><span>Duration:</span> <strong>{days} day{'s' if days > 1 else ''}</strong></div>
                    <div class="detail-row"><span>Amount Paid:</span> <span class="amount">KES {amount:,.2f}</span></div>
                    <div class="detail-row"><span>Start Date:</span> <strong>{start_str}</strong></div>
                    <div class="detail-row"><span>End Date:</span> <strong>{end_str}</strong></div>
                </div>

                <p>Your {item_type} will appear with a "Sponsored" badge on relevant pages across Wananchimart, giving it extra visibility.</p>

                <p style="text-align: center;">
                    <a href="{settings.FRONTEND_URL}/vendor/ads" class="button">View My Ads</a>
                </p>

                <p>Thank you for advertising on Wananchimart!</p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Your sponsored ad for {item_name} is now live on Wananchimart!

    Ad Details:
    - Item: {item_name}
    - Type: {type_label}
    - Duration: {days} day{'s' if days > 1 else ''}
    - Amount Paid: KES {amount:,.2f}
    - Start Date: {start_str}
    - End Date: {end_str}

    Your {item_type} will appear with a "Sponsored" badge on relevant pages.

    View your ads at: {settings.FRONTEND_URL}/vendor/ads

    Thank you for advertising on Wananchimart!

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send sponsored ad email: {e}")
        return False

    return False


def send_verification_rejected_email(user, vendor_profile, reason=''):
    """Send email when verification is rejected"""
    subject = "Verification Update - Wananchimart"

    reason_html = f'<p><strong>Reason:</strong> {reason}</p>' if reason else ''
    reason_text = f'\nReason: {reason}' if reason else ''

    html_message = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .button {{ display: inline-block; background: #f97316; color: white; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin: 20px 0; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            .reason-box {{ background: #fef2f2; border-left: 4px solid #ef4444; padding: 15px; margin: 20px 0; border-radius: 0 8px 8px 0; }}
            h1 {{ margin: 0; font-size: 24px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Verification Update</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{user.full_name}</strong>,</p>

                <p>Unfortunately, your verification request for <strong>{vendor_profile.shop_name}</strong> was not approved at this time.</p>

                {f'<div class="reason-box">{reason_html}</div>' if reason else ''}

                <p>You can resubmit your verification request with updated information.</p>

                <p style="text-align: center;">
                    <a href="{settings.FRONTEND_URL}/vendor/verify" class="button">Resubmit Verification</a>
                </p>

                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">


            </div>
        </div>
    </body>
    </html>
    """

    plain_message = f"""
    Hi {user.full_name},

    Unfortunately, your verification request for {vendor_profile.shop_name} was not approved.{reason_text}

    You can resubmit with updated information at: {settings.FRONTEND_URL}/vendor/verify

    Best regards,
    The Wananchimart Team
    """

    try:
        if user.email:
            send_mail(
                subject=subject,
                message=plain_message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[user.email],
                html_message=html_message,
                fail_silently=False,
            )
            return True
    except Exception as e:
        print(f"Failed to send verification rejected email: {e}")
        return False

    return False


def _build_bulk_email_html(recipient_name, body_content):
    """Build branded HTML email for bulk sends"""
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }}
            .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
            .header {{ background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }}
            .content {{ background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }}
            .footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
            h1 {{ margin: 0; font-size: 28px; }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Wananchimart</h1>
            </div>
            <div class="content">
                <p>Hi <strong>{recipient_name}</strong>,</p>
                {body_content}
                <p>Best regards,<br><strong>The Wananchimart Team</strong></p>
            </div>
            <div class="footer">
                <p>You received this email because you are a member of Wananchimart.</p>
            </div>
        </div>
    </body>
    </html>
    """


def send_bulk_email(subject, body_html, recipients, campaign_id=None):
    """
    Send bulk email using a single SMTP connection.
    recipients: list of dicts with 'name' and 'email' keys.
    campaign_id: optional EmailCampaign pk to update with results.
    Designed to run in a background thread — always updates campaign on exit.
    """
    from django import db as django_db

    sent_count = 0
    failed_count = 0
    failed_emails = []
    error_message = ''

    try:
        # Close any stale DB connections inherited from the parent thread
        django_db.connections.close_all()

        connection = get_connection()
        connection.open()

        for recipient in recipients:
            name = recipient.get('name', '')
            email = recipient.get('email', '')
            if not email:
                failed_count += 1
                failed_emails.append(email)
                continue

            html_message = _build_bulk_email_html(name, body_html)
            plain_message = strip_tags(html_message)

            try:
                send_mail(
                    subject=subject,
                    message=plain_message,
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[email],
                    html_message=html_message,
                    connection=connection,
                    fail_silently=False,
                )
                sent_count += 1
            except Exception as e:
                print(f"Failed to send to {email}: {e}")
                failed_count += 1
                failed_emails.append(email)

        try:
            connection.close()
        except Exception:
            pass
    except Exception as e:
        error_message = str(e)
        print(f"SMTP connection error: {e}")
        failed_count = len(recipients) - sent_count
        failed_emails = [r.get('email', '') for r in recipients[sent_count:]]
    finally:
        # ALWAYS update campaign — even if thread crashed
        if campaign_id:
            try:
                django_db.connections.close_all()
                from accounts.models import EmailCampaign
                from django.utils import timezone as tz
                campaign = EmailCampaign.objects.get(pk=campaign_id)
                campaign.sent_count = sent_count
                campaign.failed_count = failed_count
                campaign.failed_emails = ','.join(failed_emails)
                campaign.error_message = error_message
                campaign.status = 'failed' if sent_count == 0 and failed_count > 0 else 'completed'
                campaign.completed_at = tz.now()
                campaign.save()
            except Exception as e:
                print(f"Failed to update campaign {campaign_id}: {e}")

    return {
        'sent_count': sent_count,
        'failed_count': failed_count,
        'failed_emails': failed_emails,
    }
