from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.core.mail import get_connection
import threading

from django.template.loader import render_to_string

from core.logger import logger


def get_info_connection():
    """
    Get the email connection and sender email from settings.
    """
    connection = get_connection(host=settings.EMAIL_HOST,
                                port=settings.EMAIL_PORT,
                                username=settings.EMAIL_HOST_USER,
                                password=settings.EMAIL_HOST_PASSWORD,
                                use_tls=settings.EMAIL_USE_TLS)
    return connection, settings.EMAIL_HOST_USER


def send_support_email_async(name, country_code, phone, email, subject, message):
    """Background email task"""

    def task():
        send_support_email(name, country_code, phone, email, subject, message)

    threading.Thread(target=task).start()


# def request_reset_email_async(email, name, otp):
#     """Background email task"""
#
#     def task():
#         request_reset_email(email, name, otp)
#
#     threading.Thread(target=task).start()


def send_support_email(name, country_code, phone, email, subject, message):
    """
    Send an email of contact us to the user.
    """
    print('>>>>>>>>>>>>>>>in mail')
    connection, from_email = get_info_connection()
    app_name = 'Premium Crap'
    html_content = f"""
        <p><strong>Name:</strong> {name}</p>
        <p><strong>Email:</strong> {email}</p>
        <p><strong>Phone:</strong> {country_code} {phone}</p>
        <p><strong>Subject:</strong> {subject}</p>
        <p><strong>Message:</strong> {message}</p>
    """
    subject = f"Contact Us with {app_name} - {subject}"
    body = html_content
    send_from_email = f"{app_name} {email}"
    to_email = from_email
    email_message = EmailMultiAlternatives(subject, body, send_from_email, [to_email], connection=connection)
    email_message.content_subtype = 'html'
    try:
        sent = email_message.send()
        print(f"Email sent count: {sent}")
    except Exception as e:
        logger.error("Error in send_contact_us_email", exc_info=True)
        print("Email sending failed:", str(e))


# def request_reset_email(email, name, otp):
#     """
#     Send an email with OTP for password reset to the user.
#     """
#     connection, from_email = get_info_connection()
#     print(f"OTP: {otp}")
#     data = {"name": name, "otp": otp, "app_name": settings.APP_NAME, "base_url": settings.BASE_URL}
#     body = render_to_string('forgot_pass_otp.html', context=data)
#     subject = 'Forgot Password'
#     from_email = f'{settings.APP_NAME} <{from_email}>'
#     email_message = EmailMultiAlternatives(subject, body, from_email, [email], connection=connection)
#     email_message.content_subtype = 'html'
#     try:
#         sent = email_message.send()
#         print(f"Email sent count: {sent}")
#     except Exception as e:
#         logger.error(f"Error in request_reset_email: {e}")
#         print("Email sending failed:", str(e))
