from django.contrib import admin
from django.utils.html import format_html

from .models import (
    AuthenticationNonce,
    EDSCertificate,
    FailedAuthenticationAttempt,
    SecurityLog,
    SignatureVerificationLog,
)


@admin.register(EDSCertificate)
class EDSCertificateAdmin(admin.ModelAdmin):
    """Admin interface for EDS certificates."""

    list_display = (
        "subject",
        "user_link",
        "serial_number_short",
        "validity_status",
        "valid_to_date",
        "is_revoked",
        "created_at",
    )
    list_filter = ("is_revoked", "created_at", "valid_to")
    search_fields = ("subject", "user__username", "serial_number", "thumbprint")
    readonly_fields = (
        "thumbprint",
        "created_at",
        "updated_at",
        "public_key_pem",
    )

    fieldsets = (
        (
            "User",
            {"fields": ("user",)},
        ),
        (
            "Certificate Info",
            {"fields": ("subject", "issuer", "serial_number", "thumbprint")},
        ),
        (
            "Public Key",
            {"fields": ("public_key_pem",), "classes": ("collapse",)},
        ),
        (
            "Validity",
            {"fields": ("valid_from", "valid_to")},
        ),
        (
            "Status",
            {"fields": ("is_revoked", "revoked_at")},
        ),
        (
            "Timestamps",
            {"fields": ("created_at", "updated_at"), "classes": ("collapse",)},
        ),
    )

    def user_link(self, obj):
        """Link to user."""
        return f"{obj.user.username}"

    user_link.short_description = "User"

    def serial_number_short(self, obj):
        """Shortened serial number."""
        return (
            obj.serial_number[:20] + "..."
            if len(obj.serial_number) > 20
            else obj.serial_number
        )

    serial_number_short.short_description = "Serial Number"

    def validity_status(self, obj):
        """Color-coded validity status."""
        if obj.is_revoked:
            status = "🔴 Revoked"
            color = "red"
        elif obj.is_valid():
            status = "🟢 Valid"
            color = "green"
        else:
            status = "🟡 Expired"
            color = "orange"

        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>', color, status
        )

    validity_status.short_description = "Status"

    def valid_to_date(self, obj):
        """Valid to date."""
        return obj.valid_to.strftime("%Y-%m-%d")

    valid_to_date.short_description = "Valid To"


@admin.register(AuthenticationNonce)
class AuthenticationNonceAdmin(admin.ModelAdmin):
    """Admin interface for authentication nonces."""

    list_display = ("user", "nonce_short", "is_used", "expires_at", "created_at")
    list_filter = ("is_used", "created_at", "expires_at")
    search_fields = ("user__username", "nonce")
    readonly_fields = ("nonce", "created_at")

    fieldsets = (
        (
            "Nonce",
            {"fields": ("nonce",)},
        ),
        (
            "User",
            {"fields": ("user",)},
        ),
        (
            "Status",
            {"fields": ("is_used", "used_at")},
        ),
        (
            "Validity",
            {"fields": ("expires_at",)},
        ),
        (
            "Timestamps",
            {"fields": ("created_at",), "classes": ("collapse",)},
        ),
    )

    def nonce_short(self, obj):
        """Shortened nonce."""
        return obj.nonce[:20] + "..."

    nonce_short.short_description = "Nonce"


@admin.register(SignatureVerificationLog)
class SignatureVerificationLogAdmin(admin.ModelAdmin):
    """Admin interface for signature verification audit trail."""

    list_display = (
        "user_or_anon",
        "status_badge",
        "ip_address",
        "created_at",
    )
    list_filter = ("status", "created_at")
    search_fields = ("user__username", "ip_address", "message")
    readonly_fields = ("created_at", "user", "certificate", "status", "message")

    fieldsets = (
        (
            "User & Certificate",
            {"fields": ("user", "certificate")},
        ),
        (
            "Verification",
            {"fields": ("status", "message")},
        ),
        (
            "Request Context",
            {"fields": ("ip_address", "user_agent")},
        ),
        (
            "Timestamp",
            {"fields": ("created_at",), "classes": ("collapse",)},
        ),
    )

    def user_or_anon(self, obj):
        """Display username or Anonymous."""
        return obj.user.username if obj.user else "Anonymous"

    user_or_anon.short_description = "User"

    def status_badge(self, obj):
        """Color-coded status badge."""
        colors = {
            "success": "green",
            "failed_signature": "red",
            "failed_nonce": "red",
            "failed_cert": "red",
            "failed_revoked": "red",
            "failed_expired": "orange",
            "failed_invalid_format": "red",
            "error": "red",
        }
        color = colors.get(obj.status, "gray")
        return format_html(
            '<span style="background-color: {}; color: white; padding: 3px 10px; border-radius: 3px;">{}</span>',
            color,
            obj.get_status_display(),
        )

    status_badge.short_description = "Status"


@admin.register(FailedAuthenticationAttempt)
class FailedAuthenticationAttemptAdmin(admin.ModelAdmin):
    """Admin interface for failed authentication attempts (rate limiting)."""

    list_display = (
        "username",
        "attempt_type_badge",
        "attempt_number",
        "ip_address",
        "locked_badge",
        "timestamp",
    )
    list_filter = ("attempt_type", "is_locked", "timestamp")
    search_fields = ("username", "ip_address")
    readonly_fields = ("timestamp", "username", "ip_address")

    fieldsets = (
        (
            "Attempt",
            {"fields": ("username", "attempt_type", "reason")},
        ),
        (
            "Rate Limiting",
            {"fields": ("attempt_number", "is_locked")},
        ),
        (
            "Request Context",
            {"fields": ("ip_address", "user_agent", "certificate_serial")},
        ),
        (
            "Timestamp",
            {"fields": ("timestamp",), "classes": ("collapse",)},
        ),
    )

    def attempt_type_badge(self, obj):
        """Color-coded attempt type badge."""
        colors = {
            "eds_signature": "red",
            "certificate_mismatch": "orange",
            "invalid_nonce": "orange",
            "certificate_revoked": "red",
            "certificate_expired": "yellow",
            "signature_invalid": "red",
        }
        color = colors.get(obj.attempt_type, "gray")
        return format_html(
            '<span style="background-color: {}; color: white; padding: 3px 10px; border-radius: 3px;">{}</span>',
            color,
            obj.get_attempt_type_display(),
        )

    attempt_type_badge.short_description = "Type"

    def locked_badge(self, obj):
        """Locked status badge."""
        if obj.is_locked:
            return format_html(
                '<span style="background-color: red; color: white; padding: 3px 10px; border-radius: 3px;">🔒 LOCKED</span>'
            )
        return "No"

    locked_badge.short_description = "Locked"


@admin.register(SecurityLog)
class SecurityLogAdmin(admin.ModelAdmin):
    """Read-only admin interface for security audit trail."""

    list_display = ("event_time", "event_type", "ip_address", "user")
    list_filter = ("event_type", "event_time")
    search_fields = ("ip_address", "user__username")
    readonly_fields = ("event_time", "event_type", "ip_address", "user", "details")
    actions = None

    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 False