from django.contrib import admin, messages
from django.utils import timezone
from unfold.admin import ModelAdmin, TabularInline
from unfold.decorators import display

from core.admin_ui import PortalAdminMixin
from .models import FormTemplate, FormTemplateField, ReusableTemplate, TemplateCategory, TemplateUsage


class FormTemplateFieldInline(TabularInline):
    model = FormTemplateField
    extra = 1
    tab = True
    fields = ("sort_order", "label", "key", "field_type", "required", "is_active", "placeholder", "help_text", "options")
    ordering = ("sort_order", "id")


@admin.action(description="Duplicar templates selecionados")
def duplicate_reusable_templates(modeladmin, request, queryset):
    created = 0
    for template in queryset:
        base_code = f"{template.code}-copia"
        code = base_code
        suffix = 2
        while ReusableTemplate.objects.filter(code=code).exists():
            code = f"{base_code}-{suffix}"
            suffix += 1
        template.pk = None
        template.public_id = None
        template.name = f"{template.name} — cópia"
        template.code = code
        template.is_default = False
        template.usage_count = 0
        template.last_used_at = None
        template.save()
        created += 1
    modeladmin.message_user(request, f"{created} templates duplicados.", messages.SUCCESS)


@admin.action(description="Duplicar formulários selecionados")
def duplicate_form_templates(modeladmin, request, queryset):
    created = 0
    for form in queryset.prefetch_related("fields"):
        fields = list(form.fields.all())
        base_code = f"{form.code}-copia"
        code = base_code
        suffix = 2
        while FormTemplate.objects.filter(code=code).exists():
            code = f"{base_code}-{suffix}"
            suffix += 1
        old_name = form.name
        form.pk = None
        form.public_id = None
        form.name = f"{old_name} — cópia"
        form.code = code
        form.version = 1
        form.save()
        for field in fields:
            field.pk = None
            field.public_id = None
            field.form_template = form
            field.save()
        created += 1
    modeladmin.message_user(request, f"{created} formulários duplicados.", messages.SUCCESS)


@admin.register(TemplateCategory)
class TemplateCategoryAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "folder_copy"
    portal_kicker = "BIBLIOTECA"
    portal_description = "Categorias editoriais que organizam emails, formulários, documentos e respostas reutilizáveis."
    portal_tone = "yellow"
    portal_stats = (
        {"label": "Categorias", "icon": "folder_copy", "tone": "primary", "caption": "Total registado"},
        {"label": "Ativas", "icon": "check_circle", "tone": "success", "filters": {"is_active": True}, "caption": "Disponíveis"},
        {"label": "Inativas", "icon": "pause_circle", "tone": "warning", "filters": {"is_active": False}, "caption": "Arquivadas"},
    )
    portal_related_links = (
        {"label": "Centro de templates", "icon": "dashboard_customize", "url_name": "template_center"},
        {"label": "Templates reutilizáveis", "icon": "content_copy", "url_name": "admin:template_library_reusabletemplate_changelist"},
        {"label": "Formulários", "icon": "dynamic_form", "url_name": "admin:template_library_formtemplate_changelist"},
    )
    list_display = ("name", "code", "tone", "sort_order", "is_active", "updated_at")
    list_editable = ("sort_order", "is_active")
    list_filter = ("tone", "is_active")
    search_fields = ("name", "code", "description")
    fieldsets = (
        ("Categoria", {"fields": ("name", "code", "description")}),
        ("Apresentação", {"fields": ("icon", "tone", "sort_order", "is_active")}),
        ("Sistema", {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}),
    )
    readonly_fields = ("created_at", "updated_at")


@admin.register(ReusableTemplate)
class ReusableTemplateAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "content_copy"
    portal_kicker = "BIBLIOTECA"
    portal_description = "Conteúdos reutilizáveis para tickets, documentos, contratos, relatórios, checklists e mensagens."
    portal_tone = "violet"
    portal_stats = (
        {"label": "Templates", "icon": "content_copy", "tone": "primary", "caption": "Total disponível"},
        {"label": "Ativos", "icon": "check_circle", "tone": "success", "filters": {"is_active": True}, "caption": "Em utilização"},
        {"label": "No portal", "icon": "web", "tone": "cyan", "filters": {"visible_to_clients": True}, "caption": "Autorizados para clientes"},
        {"label": "Inativos", "icon": "archive", "tone": "warning", "filters": {"is_active": False}, "caption": "Arquivados"},
    )
    portal_related_links = (
        {"label": "Centro de templates", "icon": "dashboard_customize", "url_name": "template_center"},
        {"label": "Emails", "icon": "mail", "url_name": "admin:notifications_notificationtemplate_changelist"},
        {"label": "Formulários", "icon": "dynamic_form", "url_name": "admin:template_library_formtemplate_changelist"},
    )
    list_display = ("template_identity", "category", "is_active", "is_default", "visible_to_clients", "usage_count", "updated_at")
    list_filter = ("kind", "category", "is_active", "is_default", "visible_to_clients")
    search_fields = ("name", "code", "description", "subject_template", "body_template")
    autocomplete_fields = ("category",)
    list_editable = ("is_active", "visible_to_clients")
    actions = (duplicate_reusable_templates,)
    readonly_fields = ("usage_count", "last_used_at", "created_at", "updated_at")
    fieldsets = (
        ("Identificação", {"fields": ("name", "code", "kind", "category", "description")}),
        ("Conteúdo", {"fields": ("subject_template", "body_template", "html_template")}),
        ("Variáveis e pré-visualização", {"fields": ("variables", "example_context")}),
        ("Disponibilidade", {"fields": ("is_active", "is_default", "visible_to_clients")}),
        ("Utilização", {"fields": ("usage_count", "last_used_at", "created_at", "updated_at"), "classes": ("collapse",)}),
    )

    @display(description="Template", header=True)
    def template_identity(self, obj):
        return obj.name, f"{obj.get_kind_display()} · {obj.code}"


@admin.register(FormTemplate)
class FormTemplateAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "dynamic_form"
    portal_kicker = "BIBLIOTECA"
    portal_description = "Estruturas de formulários para recolha de dados, pedidos, briefings e suporte."
    portal_tone = "cyan"
    portal_stats = (
        {"label": "Formulários", "icon": "dynamic_form", "tone": "primary", "caption": "Total disponível"},
        {"label": "Ativos", "icon": "check_circle", "tone": "success", "filters": {"is_active": True}, "caption": "Prontos a usar"},
        {"label": "No portal", "icon": "web", "tone": "cyan", "filters": {"visible_to_clients": True}, "caption": "Disponíveis a clientes"},
        {"label": "Inativos", "icon": "archive", "tone": "warning", "filters": {"is_active": False}, "caption": "Arquivados"},
    )
    portal_related_links = (
        {"label": "Centro de templates", "icon": "dashboard_customize", "url_name": "template_center"},
        {"label": "Templates reutilizáveis", "icon": "content_copy", "url_name": "admin:template_library_reusabletemplate_changelist"},
        {"label": "Categorias", "icon": "folder_copy", "url_name": "admin:template_library_templatecategory_changelist"},
    )
    list_display = ("form_identity", "purpose", "fields_total", "version", "is_active", "visible_to_clients", "updated_at")
    list_filter = ("purpose", "category", "is_active", "visible_to_clients", "requires_authentication")
    search_fields = ("name", "code", "description", "intro_text")
    autocomplete_fields = ("category",)
    list_editable = ("is_active", "visible_to_clients")
    actions = (duplicate_form_templates,)
    inlines = (FormTemplateFieldInline,)
    readonly_fields = ("created_at", "updated_at")
    fieldsets = (
        ("Identificação", {"fields": ("name", "code", "category", "purpose", "description", "version")}),
        ("Textos", {"fields": ("intro_text", "success_message")}),
        ("Disponibilidade", {"fields": ("is_active", "visible_to_clients", "requires_authentication", "sort_order")}),
        ("Sistema", {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}),
    )

    @display(description="Formulário", header=True)
    def form_identity(self, obj):
        return obj.name, obj.code

    @display(description="Campos")
    def fields_total(self, obj):
        return obj.fields.count()


@admin.register(FormTemplateField)
class FormTemplateFieldAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "input"
    portal_kicker = "BIBLIOTECA"
    portal_description = "Campos reutilizáveis que compõem os formulários da biblioteca."
    portal_tone = "blue"
    list_display = ("label", "form_template", "field_type", "required", "sort_order", "is_active")
    list_filter = ("field_type", "required", "is_active", "form_template__purpose")
    search_fields = ("label", "key", "form_template__name", "help_text")
    autocomplete_fields = ("form_template",)
    list_editable = ("required", "sort_order", "is_active")


@admin.register(TemplateUsage)
class TemplateUsageAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "history"
    portal_kicker = "BIBLIOTECA"
    portal_description = "Auditoria de pré-visualizações, cópias, documentos gerados e comunicações."
    portal_tone = "grey"
    list_display = ("target", "action", "used_by", "used_at")
    list_filter = ("action", "used_at")
    search_fields = ("reusable_template__name", "form_template__name", "used_by__username")
    readonly_fields = ("reusable_template", "form_template", "action", "used_by", "context", "used_at")

    @display(description="Template")
    def target(self, obj):
        return obj.reusable_template or obj.form_template

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False
