from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from unfold.admin import ModelAdmin, TabularInline
from unfold.decorators import display

from core.admin_ui import PortalAdminMixin
from core.choices import ClientStatus
from core.status_palette import CLIENT_STATUS_LABELS
from .models import Client, ClientContact, ClientNote, ClientPortalAccess


class ClientContactInline(TabularInline):
    model = ClientContact
    extra = 0
    tab = True
    fields = ("name", "role", "email", "phone", "is_primary", "receives_billing", "receives_technical")




class ClientPortalAccessInline(TabularInline):
    model = ClientPortalAccess
    extra = 0
    tab = True
    fields = ("user", "role", "is_active", "can_view_financial", "can_view_documents", "can_manage_tickets", "last_portal_login_at")
    readonly_fields = ("last_portal_login_at",)
    autocomplete_fields = ("user",)

class ClientNoteInline(TabularInline):
    model = ClientNote
    extra = 0
    fields = ("title", "body", "is_important", "created_by")
    readonly_fields = ("created_by",)
    tab = True


@admin.register(Client)
class ClientAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "groups"
    portal_kicker = "GESTÃO COMERCIAL"
    portal_description = "Centralize contactos, serviços, pagamentos, documentos e o histórico de relacionamento de cada cliente."
    portal_tone = "blue"
    portal_stats = (
        {"label": "Clientes registados", "icon": "groups", "tone": "primary", "caption": "Carteira total"},
        {"label": "Clientes ativos", "icon": "verified_user", "tone": "success", "filters": {"status": ClientStatus.ACTIVE}, "caption": "Em acompanhamento", "query": {"status__exact": ClientStatus.ACTIVE}},
        {"label": "Com dívida", "icon": "credit_card_off", "tone": "danger", "filters": {"status": ClientStatus.DEBT}, "caption": "Requer cobrança", "query": {"status__exact": ClientStatus.DEBT}},
        {"label": "Sem email", "icon": "mark_email_unread", "tone": "warning", "filters": {"email": ""}, "caption": "Dados a completar", "query": {"email__exact": ""}},
    )
    portal_related_links = (
        {"label": "Serviços", "icon": "inventory_2", "url_name": "admin:services_service_changelist"},
        {"label": "Pedidos de suporte", "icon": "support_agent", "url_name": "admin:support_supportticket_changelist"},
    )

    list_display = ("identity", "show_status", "phone", "preferred_payment_method", "service_count", "updated_at")
    list_filter = ("status", "client_type", "preferred_payment_method", "portal_access_enabled")
    search_fields = ("name", "legal_name", "nif", "email", "alternative_email", "phone")
    readonly_fields = ("public_id", "created_at", "updated_at")
    inlines = (ClientContactInline, ClientPortalAccessInline, ClientNoteInline)
    list_filter_sheet = False
    list_fullwidth = True

    fieldsets = (
        ("Identificação", {"fields": ("client_type", "name", "legal_name", "nif", "status"), "description": "Dados que identificam o cliente e o respetivo estado comercial."}),
        ("Contactos", {"fields": ("email", "alternative_email", "phone", "address"), "description": "Contactos principais usados em notificações, cobranças e suporte."}),
        ("Gestão", {"fields": ("preferred_payment_method", "portal_access_enabled", "internal_notes"), "description": "Preferências operacionais e observações visíveis apenas no backoffice."}),
        ("Sistema", {"fields": ("public_id", "created_at", "updated_at"), "classes": ("collapse",)}),
    )

    @display(description="Cliente", header=True)
    def identity(self, obj):
        return obj.name, obj.email or "Sem email"

    @display(description="Estado", label=CLIENT_STATUS_LABELS, ordering="status")
    def show_status(self, obj):
        return obj.get_status_display()

    @display(description="Serviços")
    def service_count(self, obj):
        return obj.services.count()

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            if isinstance(instance, ClientNote) and not instance.created_by_id:
                instance.created_by = request.user
            instance.save()
        formset.save_m2m()


@admin.register(ClientContact)
class ClientContactAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "contact_phone"
    portal_kicker = "CLIENTES"
    portal_description = "Contactos alternativos e responsáveis por comunicações financeiras ou técnicas."
    portal_tone = "cyan"
    portal_stats = (
        {"label": "Contactos", "icon": "contact_phone", "tone": "primary", "caption": "Total registado"},
        {"label": "Principais", "icon": "star", "tone": "success", "filters": {"is_primary": True}, "caption": "Contacto preferencial"},
        {"label": "Financeiros", "icon": "receipt_long", "tone": "warning", "filters": {"receives_billing": True}, "caption": "Recebem cobranças"},
        {"label": "Técnicos", "icon": "engineering", "tone": "violet", "filters": {"receives_technical": True}, "caption": "Recebem alertas técnicos"},
    )
    list_display = ("name", "client", "email", "phone", "is_primary")
    list_filter = ("is_primary", "receives_billing", "receives_technical")
    search_fields = ("name", "client__name", "email", "phone")
    autocomplete_fields = ("client",)
    list_fullwidth = True
    fieldsets = (
        ("Contacto", {"fields": ("client", "name", "role", "email", "phone")}),
        ("Preferências", {"fields": ("is_primary", "receives_billing", "receives_technical")}),
    )


@admin.register(ClientNote)
class ClientNoteAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "sticky_note_2"
    portal_kicker = "CLIENTES"
    portal_description = "Notas internas para preservar contexto, decisões e informação importante sobre o relacionamento."
    portal_tone = "amber"
    portal_stats = (
        {"label": "Notas", "icon": "sticky_note_2", "tone": "primary", "caption": "Histórico total"},
        {"label": "Importantes", "icon": "priority_high", "tone": "danger", "filters": {"is_important": True}, "caption": "Destacadas"},
    )
    list_display = ("title", "client", "is_important", "created_by", "created_at")
    list_filter = ("is_important", "created_at")
    search_fields = ("title", "body", "client__name")
    autocomplete_fields = ("client",)
    readonly_fields = ("created_by", "created_at", "updated_at")
    list_fullwidth = True
    fieldsets = (
        ("Nota", {"fields": ("client", "title", "body", "is_important")}),
        ("Autoria", {"fields": ("created_by", "created_at", "updated_at")}),
    )

    def save_model(self, request, obj, form, change):
        if not obj.created_by_id:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(ClientPortalAccess)
class ClientPortalAccessAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "account_circle"
    portal_kicker = "PORTAL DO CLIENTE"
    portal_description = "Associe utilizadores Django aos clientes e controle o acesso a pagamentos, documentos e tickets."
    portal_tone = "amber"
    portal_stats = (
        {"label": "Acessos", "icon": "account_circle", "tone": "primary", "caption": "Utilizadores associados"},
        {"label": "Ativos", "icon": "verified_user", "tone": "success", "filters": {"is_active": True}, "caption": "Podem entrar no portal"},
        {"label": "Inativos", "icon": "person_off", "tone": "danger", "filters": {"is_active": False}, "caption": "Acesso bloqueado"},
    )
    list_display = ("user", "client", "role", "is_active", "can_view_financial", "can_manage_tickets", "last_portal_login_at", "preview_link")
    list_filter = ("is_active", "role", "can_view_financial", "can_view_documents", "can_manage_tickets")
    search_fields = ("user__username", "user__email", "user__first_name", "user__last_name", "client__name", "client__email")
    autocomplete_fields = ("client", "user")
    readonly_fields = ("invited_at", "accepted_at", "last_portal_login_at", "created_at", "updated_at")
    list_fullwidth = True
    fieldsets = (
        ("Acesso", {"fields": ("client", "user", "role", "is_active")}),
        ("Permissões", {"fields": ("can_view_financial", "can_view_documents", "can_manage_tickets")}),
        ("Atividade", {"fields": ("invited_at", "accepted_at", "last_portal_login_at")}),
        ("Sistema", {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}),
    )

    @display(description="Teste")
    def preview_link(self, obj):
        if not obj.is_active or not obj.user.is_active or not obj.client.portal_access_enabled:
            return "Indisponível"
        return format_html(
            '<a class="k4w-inline-preview" href="{}">Pré-visualizar</a>',
            reverse("client_preview_center") + f"?q={obj.user.username}",
        )
