from django.contrib import admin
from django.utils import timezone
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 TASK_STATUS_LABELS
from .models import InternalTask


@admin.action(description="Marcar tarefas selecionadas como concluídas")
def mark_done(modeladmin, request, queryset):
    queryset.update(status=InternalTask.Status.DONE, completed_at=timezone.now())


@admin.action(description="Marcar tarefas selecionadas como em curso")
def mark_in_progress(modeladmin, request, queryset):
    queryset.update(status=InternalTask.Status.IN_PROGRESS, completed_at=None)


@admin.register(InternalTask)
class InternalTaskAdmin(PortalAdminMixin, ModelAdmin):
    portal_icon = "task_alt"
    portal_kicker = "OPERAÇÕES"
    portal_description = "Planeie renovações, contactos, verificações técnicas e outras ações internas com prioridade e responsável."
    portal_tone = "blue"
    portal_stats = (
        {"label": "Tarefas", "icon": "task_alt", "tone": "primary", "caption": "Histórico total"},
        {"label": "Por fazer", "icon": "check_box_outline_blank", "tone": "warning", "filters": {"status": InternalTask.Status.TODO}, "caption": "Fila de trabalho"},
        {"label": "Em curso", "icon": "pending_actions", "tone": "primary", "filters": {"status": InternalTask.Status.IN_PROGRESS}, "caption": "Em execução"},
        {"label": "Atrasadas", "icon": "running_with_errors", "tone": "danger", "method": "count_overdue", "caption": "Ultrapassaram o prazo"},
    )
    portal_related_links = (
        {"label": "Renovações", "icon": "event_repeat", "url_name": "admin:billing_renewal_changelist"},
        {"label": "Suporte", "icon": "support_agent", "url_name": "admin:support_supportticket_changelist"},
        {"label": "Ativos técnicos", "icon": "developer_board", "url_name": "admin:technical_technicalasset_changelist"},
    )

    list_display = ("task_identity", "client", "service", "priority_label", "status_label", "due_date", "overdue_label", "assigned_to")
    list_filter = ("task_type", "priority", "status", "assigned_to", ("due_date", RangeDateFilter))
    search_fields = ("title", "description", "client__name", "service__name")
    autocomplete_fields = ("client", "service", "renewal", "assigned_to")
    readonly_fields = ("public_id", "completed_at", "created_at", "updated_at")
    actions = (mark_in_progress, mark_done)
    list_filter_submit = True
    list_fullwidth = True

    fieldsets = (
        ("Tarefa", {"fields": ("title", "task_type", "description"), "description": "Objetivo e natureza da ação a executar."}),
        ("Contexto", {"fields": ("client", "service", "renewal"), "description": "Registos relacionados que ajudam a executar a tarefa."}),
        ("Planeamento", {"fields": ("assigned_to", "priority", "status", "due_date", "completed_at"), "description": "Responsável, urgência, prazo e evolução."}),
        ("Sistema", {"fields": ("public_id", "created_at", "updated_at"), "classes": ("collapse",)}),
    )

    def count_overdue(self, request, queryset):
        return queryset.filter(due_date__lt=timezone.localdate()).exclude(status__in=(InternalTask.Status.DONE, InternalTask.Status.CANCELLED)).count()

    @display(description="Tarefa", header=True)
    def task_identity(self, obj):
        return obj.title, obj.get_task_type_display()

    @display(description="Prioridade", label={
        InternalTask.Priority.LOW: "info",
        InternalTask.Priority.NORMAL: "primary",
        InternalTask.Priority.HIGH: "warning",
        InternalTask.Priority.URGENT: "danger",
    }, ordering="priority")
    def priority_label(self, obj):
        return obj.get_priority_display()

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

    @display(description="Atrasada", boolean=True)
    def overdue_label(self, obj):
        return obj.is_overdue
