from django.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404, render

from notifications.models import NotificationTemplate
from .models import FormTemplate, ReusableTemplate, TemplateCategory, TemplateUsage


@staff_member_required
def template_center(request):
    email_templates = NotificationTemplate.objects.order_by("notification_type", "code")
    reusable_templates = ReusableTemplate.objects.select_related("category").order_by("kind", "name")
    forms = FormTemplate.objects.select_related("category").prefetch_related("fields").order_by("sort_order", "name")
    categories = TemplateCategory.objects.filter(is_active=True).order_by("sort_order", "name")
    context = {
        **admin.site.each_context(request),
        "title": "Centro de templates",
        "email_templates": email_templates[:12],
        "reusable_templates": reusable_templates[:12],
        "forms": forms[:12],
        "categories": categories,
        "counts": {
            "emails": email_templates.count(),
            "reusable": reusable_templates.count(),
            "forms": forms.count(),
            "active": email_templates.filter(is_active=True).count()
            + reusable_templates.filter(is_active=True).count()
            + forms.filter(is_active=True).count(),
        },
    }
    return render(request, "admin/template_center.html", context)


@staff_member_required
def reusable_template_preview(request, pk):
    template = get_object_or_404(ReusableTemplate.objects.select_related("category"), pk=pk)
    TemplateUsage.objects.create(reusable_template=template, action=TemplateUsage.Action.PREVIEW, used_by=request.user)
    return render(
        request,
        "admin/reusable_template_preview.html",
        {
            **admin.site.each_context(request),
            "title": f"Pré-visualização — {template.name}",
            "template_object": template,
            "rendered_subject": template.render_subject(),
            "rendered_body": template.render_body(),
            "rendered_html": template.render_html(),
        },
    )


@staff_member_required
def form_template_preview(request, pk):
    form = get_object_or_404(FormTemplate.objects.prefetch_related("fields"), pk=pk)
    TemplateUsage.objects.create(form_template=form, action=TemplateUsage.Action.PREVIEW, used_by=request.user)
    return render(
        request,
        "admin/form_template_preview.html",
        {
            **admin.site.each_context(request),
            "title": f"Pré-visualização — {form.name}",
            "form_template": form,
            "form_fields": form.fields.filter(is_active=True).order_by("sort_order", "id"),
        },
    )
