from django.contrib import admin
from django.db.models import F
from unfold.admin import ModelAdmin
from unfold.contrib.filters.admin import RangeDateFilter
from unfold.decorators import display

from core.admin_ui import PortalAdminMixin
from core.status_palette import WEBSITE_STATUS_LABELS
from .models import WebsiteProject


@admin.register(WebsiteProject)
class WebsiteProjectAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "web"
    portal_kicker = "PROJETOS WEB"
    portal_description = "Acompanhe o ciclo de vida dos websites, valores contratados, entregas e serviços recorrentes associados."
    portal_tone = "violet"
    portal_stats = (
        {"label": "Projetos", "icon": "web", "tone": "primary", "caption": "Total registado"},
        {"label": "Em desenvolvimento", "icon": "code", "tone": "primary", "filters": {"status": WebsiteProject.Status.DEVELOPMENT}, "caption": "Trabalho em curso"},
        {"label": "A aguardar cliente", "icon": "hourglass_top", "tone": "warning", "filters": {"status": WebsiteProject.Status.WAITING}, "caption": "Dependências externas"},
        {"label": "Com valor em falta", "icon": "request_quote", "tone": "danger", "method": "count_outstanding", "caption": "Requer acompanhamento"},
    )
    portal_related_links = (
        {"label": "Clientes", "icon": "groups", "url_name": "admin:clients_client_changelist"},
        {"label": "Serviços", "icon": "inventory_2", "url_name": "admin:services_service_changelist"},
        {"label": "Domínios", "icon": "language", "url_name": "admin:domains_domain_changelist"},
    )

    list_display = ("project_identity", "client", "primary_domain", "show_status", "start_date", "delivery_date", "contracted_value", "outstanding")
    list_filter = ("status", "technology", "partner", ("start_date", RangeDateFilter), ("delivery_date", RangeDateFilter))
    search_fields = ("title", "client__name", "primary_domain__domain_name", "technology", "theme_name", "notes")
    autocomplete_fields = ("client", "primary_domain", "recurring_services")
    filter_horizontal = ("recurring_services",)
    readonly_fields = ("public_id", "outstanding", "created_at", "updated_at")
    list_fullwidth = True

    fieldsets = (
        ("Projeto", {"fields": ("client", "title", "primary_domain", "status", "start_date", "delivery_date"), "description": "Identificação, calendário e estado atual do projeto."}),
        ("Tecnologia", {"fields": ("technology", "theme_name", "repository_reference", "partner"), "description": "Referências técnicas e comerciais do desenvolvimento."}),
        ("Financeiro", {"fields": ("contracted_value", "historical_received_value", "outstanding"), "description": "Resumo financeiro histórico do projeto."}),
        ("Serviços recorrentes", {"fields": ("recurring_services",), "description": "Alojamento, domínio, manutenção ou outros serviços resultantes do projeto."}),
        ("Observações", {"fields": ("notes",)}),
        ("Sistema", {"fields": ("public_id", "created_at", "updated_at"), "classes": ("collapse",)}),
    )

    def count_outstanding(self, request, queryset):
        return queryset.filter(contracted_value__gt=F("historical_received_value")).count()

    @display(description="Projeto", header=True)
    def project_identity(self, obj):
        return obj.title, obj.technology or "Tecnologia por definir"

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

    @display(description="Por receber")
    def outstanding(self, obj):
        return f"{obj.historical_outstanding_value:.2f} €"
