"""
Themis admin configuration.
"""
from django.contrib import admin

from themis.models import UserAPIKey, UserNotification, UserProfile


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    """Admin interface for UserProfile."""

    list_display = [
        "user",
        "home_timezone",
        "theme_mode",
        "theme_name",
        "notifications_enabled",
        "is_traveling",
        "created_at",
    ]
    list_filter = [
        "theme_mode",
        "date_format",
        "time_format",
        "week_start",
        "notifications_enabled",
        "browser_notifications_enabled",
    ]
    search_fields = [
        "user__username",
        "user__email",
        "user__first_name",
        "user__last_name",
    ]
    readonly_fields = ["created_at", "updated_at", "effective_timezone", "is_traveling"]
    raw_id_fields = ["user"]

    fieldsets = (
        ("User", {"fields": ("user",)}),
        (
            "Timezone Settings",
            {
                "fields": (
                    "home_timezone",
                    "current_timezone",
                    "effective_timezone",
                    "is_traveling",
                ),
            },
        ),
        (
            "Display Preferences",
            {
                "fields": (
                    "date_format",
                    "time_format",
                    "thousand_separator",
                    "week_start",
                ),
            },
        ),
        (
            "Theme Settings",
            {"fields": ("theme_mode", "theme_name", "dark_theme_name")},
        ),
        (
            "Notification Preferences",
            {
                "fields": (
                    "notifications_enabled",
                    "notifications_min_level",
                    "browser_notifications_enabled",
                    "notification_retention_days",
                ),
            },
        ),
        (
            "Metadata",
            {
                "fields": ("created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )


@admin.register(UserAPIKey)
class UserAPIKeyAdmin(admin.ModelAdmin):
    """Admin interface for UserAPIKey."""

    list_display = [
        "service_name",
        "key_type",
        "user",
        "is_active",
        "last_used_at",
        "created_at",
    ]
    list_filter = ["key_type", "is_active"]
    search_fields = ["service_name", "label", "user__username"]
    readonly_fields = ["id", "masked_value", "created_at", "updated_at"]
    raw_id_fields = ["user"]

    fieldsets = (
        (
            "Key Identity",
            {"fields": ("id", "user", "service_name", "key_type", "label")},
        ),
        (
            "Value",
            {
                "fields": ("masked_value",),
                "description": "The encrypted key value. Only the last 4 characters are shown.",
            },
        ),
        (
            "Documentation",
            {"fields": ("instructions", "help_url")},
        ),
        (
            "Status",
            {"fields": ("is_active", "last_used_at", "expires_at")},
        ),
        (
            "Metadata",
            {
                "fields": ("created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )


@admin.register(UserNotification)
class UserNotificationAdmin(admin.ModelAdmin):
    """Admin interface for UserNotification."""

    list_display = [
        "title",
        "user",
        "level",
        "source_app",
        "is_read",
        "is_dismissed",
        "created_at",
    ]
    list_filter = [
        "level",
        "is_read",
        "is_dismissed",
        "source_app",
    ]
    search_fields = [
        "title",
        "message",
        "user__username",
        "source_app",
        "source_model",
    ]
    readonly_fields = [
        "id",
        "created_at",
        "updated_at",
        "read_at",
        "dismissed_at",
        "level_css_class",
    ]
    raw_id_fields = ["user"]
    date_hierarchy = "created_at"

    fieldsets = (
        (
            "Content",
            {"fields": ("id", "user", "title", "message", "level", "url")},
        ),
        (
            "Source Tracking",
            {
                "fields": ("source_app", "source_model", "source_id"),
                "description": "Tracks which app/model created this notification.",
            },
        ),
        (
            "State",
            {
                "fields": (
                    "is_read",
                    "read_at",
                    "is_dismissed",
                    "dismissed_at",
                    "expires_at",
                ),
            },
        ),
        (
            "Metadata",
            {
                "fields": ("created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )

    actions = ["mark_as_read", "mark_as_dismissed"]

    @admin.action(description="Mark selected notifications as read")
    def mark_as_read(self, request, queryset):
        from django.utils import timezone

        count = queryset.filter(is_read=False).update(
            is_read=True, read_at=timezone.now()
        )
        self.message_user(request, f"{count} notification(s) marked as read.")

    @admin.action(description="Mark selected notifications as dismissed")
    def mark_as_dismissed(self, request, queryset):
        from django.utils import timezone

        count = queryset.filter(is_dismissed=False).update(
            is_dismissed=True, dismissed_at=timezone.now()
        )
        self.message_user(
            request, f"{count} notification(s) marked as dismissed."
        )
