from django.contrib import admin
from django_otp.plugins.otp_totp.models import TOTPDevice
from unfold.admin import ModelAdmin
from unfold.decorators import display

from core.admin_ui import PortalAdminMixin

from .models import RecoveryCode, SecurityEvent, UserProfile


@admin.register(UserProfile)
class UserProfileAdmin(PortalAdminMixin, ModelAdmin):
    list_display = ("user", "job_title", "phone", "two_factor_required", "last_two_factor_at")
    search_fields = ("user__username", "user__email", "user__first_name", "user__last_name", "phone")
    list_filter = ("two_factor_required",)
    autocomplete_fields = ("user",)
    readonly_fields = ("last_two_factor_at", "created_at", "updated_at")


@admin.register(SecurityEvent)
class SecurityEventAdmin(PortalAdminMixin, ModelAdmin):
    list_display = ("created_at", "event_badge", "user", "username_entered", "ip_address")
    list_filter = ("event_type", "created_at")
    search_fields = ("user__username", "user__email", "username_entered", "ip_address")
    readonly_fields = ("user", "event_type", "username_entered", "ip_address", "user_agent", "details", "created_at")
    ordering = ("-created_at",)

    @display(description="Evento", label=True)
    def event_badge(self, obj):
        variants = {
            SecurityEvent.EventType.LOGIN_SUCCESS: "success",
            SecurityEvent.EventType.OTP_SUCCESS: "success",
            SecurityEvent.EventType.OTP_ENABLED: "success",
            SecurityEvent.EventType.LOGIN_FAILED: "danger",
            SecurityEvent.EventType.OTP_FAILED: "danger",
            SecurityEvent.EventType.OTP_DISABLED: "warning",
        }
        return obj.get_event_type_display(), variants.get(obj.event_type, "info")

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser


@admin.register(RecoveryCode)
class RecoveryCodeAdmin(PortalAdminMixin, ModelAdmin):
    list_display = ("user", "created_at", "used_at")
    list_filter = ("used_at",)
    search_fields = ("user__username", "user__email")
    readonly_fields = ("user", "code_hash", "created_at", "used_at")

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser
