from django.contrib import admin
from django.db.models import Q
from unfold.admin import ModelAdmin
from unfold.decorators import display

from core.admin_ui import PortalAdminMixin
from core.status_palette import HOSTING_STATUS_LABELS
from .models import HostingAccount


@admin.register(HostingAccount)
class HostingAccountAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "cloud"
    portal_kicker = "SERVIÇOS RECORRENTES"
    portal_description = "Visão operacional das contas de alojamento, servidores, planos, utilização de disco e configurações técnicas."
    portal_tone = "blue"
    portal_stats = (
        {"label": "Alojamentos", "icon": "cloud", "tone": "primary", "caption": "Contas registadas"},
        {"label": "Ativos", "icon": "cloud_done", "tone": "success", "filters": {"status": HostingAccount.Status.ACTIVE}, "caption": "Em produção"},
        {"label": "Suspensos / migração", "icon": "sync_problem", "tone": "warning", "method": "count_attention", "caption": "Requer acompanhamento"},
        {"label": "Sem servidor", "icon": "dns_off", "tone": "danger", "filters": {"server__isnull": True}, "caption": "Dados a completar"},
    )
    portal_related_links = (
        {"label": "Servidores", "icon": "dns", "url_name": "admin:technical_server_changelist"},
        {"label": "Domínios", "icon": "language", "url_name": "admin:domains_domain_changelist"},
        {"label": "Ativos técnicos", "icon": "developer_board", "url_name": "admin:technical_technicalasset_changelist"},
    )

    list_display = ("hosting_identity", "client_name", "primary_domain", "server", "plan_name", "show_status", "renewal_date", "disk_usage")
    list_filter = ("status", "server", "panel_type", "php_version", "service__status")
    search_fields = ("service__name", "service__client__name", "primary_domain__domain_name", "account_reference", "document_root")
    autocomplete_fields = ("service", "primary_domain", "server")
    readonly_fields = ("public_id", "renewal_date", "disk_usage", "created_at", "updated_at")
    list_fullwidth = True

    fieldsets = (
        ("Alojamento", {"fields": ("service", "primary_domain", "server", "plan_name", "status"), "description": "Relação comercial, domínio principal e infraestrutura onde a conta está alojada."}),
        ("Conta técnica", {"fields": ("panel_type", "account_reference", "document_root", "php_version"), "description": "Referências operacionais; não guardar passwords neste formulário."}),
        ("Recursos", {"fields": ("disk_quota_mb", "disk_used_mb", "disk_usage", "monthly_traffic_mb", "email_account_limit"), "description": "Capacidade contratada e utilização atual."}),
        ("Renovação", {"fields": ("renewal_date",)}),
        ("Notas", {"fields": ("notes",)}),
        ("Sistema", {"fields": ("public_id", "created_at", "updated_at"), "classes": ("collapse",)}),
    )

    def count_attention(self, request, queryset):
        return queryset.filter(status__in=(HostingAccount.Status.SUSPENDED, HostingAccount.Status.MIGRATING)).count()

    @display(description="Alojamento", header=True)
    def hosting_identity(self, obj):
        return obj.service.name, obj.plan_name or "Sem plano"

    @display(description="Cliente", ordering="service__client__name")
    def client_name(self, obj):
        return obj.service.client if obj and obj.service_id else "—"

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

    @display(description="Renovação", ordering="service__next_renewal_date")
    def renewal_date(self, obj):
        return obj.service.next_renewal_date if obj and obj.service_id else None

    @display(description="Espaço")
    def disk_usage(self, obj):
        if obj.disk_used_mb is None and obj.disk_quota_mb is None:
            return "—"
        used = obj.disk_used_mb or 0
        quota = obj.disk_quota_mb or 0
        return f"{used} / {quota} MB"
