from django.core.mail import send_mail
from django.urls import reverse
from .models import EmailConfirmation
import uuid
from django.conf import settings
from django.utils.timezone import now
from backend.core.models import Document, Organization
from django.core.mail import EmailMultiAlternatives
from django.utils.html import format_html
from backend.core.utils import generate_first_page_image
from email.mime.image import MIMEImage
from django.conf import settings
site_domain = settings.SITE_DOMAIN

def send_confirmation_email(email):
    confirmation, created = EmailConfirmation.objects.get_or_create(email=email)

    if not created:
        confirmation.uuid = uuid.uuid4()
        confirmation.created_at = now()
        confirmation.save()

    confirmation_link = f"{site_domain}{reverse('confirm_email', args=[confirmation.uuid])}"

    send_mail(
        subject="Confirm your e-mail address",
        message=f"Please click on the link to confirm your e-mail address: {confirmation_link}",
        from_email= settings.EMAIL_HOST_USER,
        recipient_list=[email]
    )

def send_payment_email(email):
    organization = Organization.objects.get(email=email)
    document = Document.objects.get(organization=organization)

    payment_link = f"{site_domain}{reverse('core:payment_page')}?email={email}"

    send_mail(
        subject="Complete your payment",
        message=f"Click the link to proceed with payment: {payment_link}",
        from_email=settings.EMAIL_HOST_USER,
        recipient_list=[email],
        fail_silently=False,
    )

def send_document_email(email, document_link, document):
    image_io = generate_first_page_image(document)

    subject = "Your Document is Ready"
    html_content = format_html(
        '<p>Your document is ready. Click the image below to view the full PDF:</p>'
        '<a href="{}" target="_blank">'
        '<img src="cid:first_page" style="width:100%;max-width:300px;" alt="Document Preview"/></a>',
        document_link
    )

    msg = EmailMultiAlternatives(subject, "", "riskletdev@gmail.com", [email])
    msg.attach_alternative(html_content, "text/html")

    image_attachment = MIMEImage(image_io.getvalue(), "image/jpeg")
    image_attachment.add_header('Content-ID', '<first_page>') 
    msg.attach(image_attachment)
    msg.send()
