from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin

from .admin_utils import register_app_models
from .models import Permission, Role, User, UserRole


class UserRoleInline(admin.TabularInline):
    model = UserRole
    fk_name = "user"
    extra = 0
    autocomplete_fields = ("role",)
    readonly_fields = ("assigned_at", "assigned_by")


@admin.register(User)
class UserAdmin(DjangoUserAdmin):
    list_display = ("id", "email", "username", "first_name", "last_name", "is_staff", "is_active")
    list_filter = ("is_staff", "is_superuser", "is_active")
    search_fields = ("email", "username", "first_name", "last_name")
    ordering = ("email",)
    inlines = [UserRoleInline]
    fieldsets = (
        (None, {"fields": ("email", "username", "password")}),
        ("Personal info", {"fields": ("first_name", "last_name", "avatar", "phone", "bio")}),
        ("Permissions", {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions")}),
        ("Important dates", {"fields": ("last_login", "date_joined")}),
    )
    add_fieldsets = (
        (None, {"classes": ("wide",), "fields": ("email", "username", "password1", "password2")}),
    )


@admin.register(Permission)
class PermissionAdmin(admin.ModelAdmin):
    list_display = ("id", "domain", "action", "label")
    list_filter = ("domain", "action")
    search_fields = ("domain", "action", "label")
    ordering = ("domain", "action")


@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
    list_display = ("id", "name", "slug", "is_system", "user_count")
    list_filter = ("is_system",)
    search_fields = ("name", "slug", "description")
    filter_horizontal = ("permissions",)
    readonly_fields = ("created_at", "updated_at")

    def user_count(self, obj):
        return obj.user_assignments.count()


@admin.register(UserRole)
class UserRoleAdmin(admin.ModelAdmin):
    list_display = ("id", "user", "role", "assigned_at", "assigned_by")
    list_filter = ("role",)
    search_fields = ("user__email", "role__name")
    autocomplete_fields = ("user", "role", "assigned_by")
    readonly_fields = ("assigned_at",)


register_app_models("core", exclude=("User", "Permission", "Role", "UserRole"))
