from django.contrib import admin
from .models import Contact, EmailMessage
from .views import preview_email
from django.shortcuts import render, get_object_or_404
from django.urls import path
from django.template.loader import get_template
from django.core.mail import EmailMultiAlternatives
from django.template.response import TemplateResponse

# Register your models here.


@admin.register(Contact, site=admin.site)
class ContactAdmin(admin.ModelAdmin):
    list_display = ("email", "name", "contacted")
    list_filter = ("email", "name", "contacted")
    search_fields = ("email", "name")


@admin.action(description="Send seelcted emails")
def send_emails(modeladmin, request, queryset):
    for email in queryset:
        success_count: int = 0
        try:
            from_email = "AI ML Operations, LLC <info@aimloperations.com>"
            d = {"title": email.subject, "content": email.body}

            html_content = get_template(f"emails/marketing_email.html").render(d)
            text_content = get_template(f"emails/marketing_email.txt").render(d)

            msg = EmailMultiAlternatives(
                email.subject, text_content, from_email, [email.recipient]
            )
            msg.attach_alternative(html_content, "text/html")

            msg.send(fail_silently=False)

            email.sent = True
            email.save()
            success_count += 1
        except Exception as e:
            raise UserWarning(e)
    modeladmin.message_user(request, f"{success_count} emails sent successfully.")


@admin.register(EmailMessage, site=admin.site)
class EmailMessageAdmin(admin.ModelAdmin):
    change_form_template = "admin/public/emailmessage/change_form.html"
    list_display = ("subject", "recipient", "sent")
    actions = [send_emails]

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path(
                "preview_email/<int:pk>/",
                self.admin_site.admin_view(self.preview_email),
                name="preview_email",
            )
        ]
        print(f"RETURNING: {custom_urls + urls}")
        return custom_urls + urls

    def preview_email(self, request, pk):
        email_instance = get_object_or_404(EmailMessage, pk=pk)
        context = {"title": email_instance.subject, "content": email_instance.body}
        return TemplateResponse(request, "public/preview_email.html", context)
