from django.contrib import admin
from django.db.models import Count
from django.utils.html import format_html

from apps.core.admin import (
    BaseModelAdmin,
    ExportActionMixin,
    QueryOptimizationMixin,
    TimestampFieldsMixin,
)

from .models import ListItem, UserList


class ListItemInline(admin.TabularInline):
    """Inline admin for ListItem within UserList admin."""

    model = ListItem
    extra = 1
    fields = ("content_type", "object_id", "rank", "notes")
    ordering = ("rank",)
    show_change_link = True


@admin.register(UserList)
class UserListAdmin(QueryOptimizationMixin, ExportActionMixin, TimestampFieldsMixin, BaseModelAdmin):
    """Admin interface for UserList."""

    list_display = (
        "title",
        "user_link",
        "category",
        "is_public",
        "item_count",
        "created_at",
        "updated_at",
    )
    list_filter = ("category", "is_public", "created_at", "updated_at")
    list_select_related = ["user"]
    list_prefetch_related = ["items"]
    search_fields = ("title", "user__username", "description")
    autocomplete_fields = ["user"]
    inlines = [ListItemInline]

    export_fields = ["id", "title", "user", "category", "is_public", "created_at", "updated_at"]
    export_filename_prefix = "user_lists"

    fieldsets = (
        (
            "Basic Information",
            {
                "fields": ("user", "title", "category", "description", "is_public"),
                "description": "List identification and categorization.",
            },
        ),
        (
            "Timestamps",
            {
                "fields": ("created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )
    readonly_fields = ("created_at", "updated_at")

    @admin.display(description="User")
    def user_link(self, obj):
        if obj.user:
            from django.urls import reverse

            url = reverse("admin:accounts_customuser_change", args=[obj.user.pk])
            return format_html('<a href="{}">{}</a>', url, obj.user.username)
        return "-"

    @admin.display(description="Items")
    def item_count(self, obj):
        return obj.items.count()

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = qs.annotate(_item_count=Count("items", distinct=True))
        return qs


@admin.register(ListItem)
class ListItemAdmin(QueryOptimizationMixin, BaseModelAdmin):
    """Admin interface for ListItem."""

    list_display = (
        "user_list",
        "content_type",
        "object_id",
        "rank",
    )
    list_filter = ("user_list__category", "content_type", "rank")
    list_select_related = ["user_list", "user_list__user", "content_type"]
