from __future__ import annotations

from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

try:
    from unfold.admin import ModelAdmin as UnfoldModelAdmin  # isort: skip
    from unfold.decorators import display  # isort: skip
except ImportError:
    UnfoldModelAdmin = admin.ModelAdmin  # type: ignore[assignment]

    def display(**kwargs):  # type: ignore[return-value]
        def decorator(fn):
            return fn
        return decorator

from simorgh.apps.app_settings.models import SettingValue


@admin.register(SettingValue)
class SettingValueAdmin(UnfoldModelAdmin):
    list_display = ("key", "scope_badge", "scope_id", "tenant", "value_preview", "updated_at")
    list_filter = ("scope", "tenant")
    search_fields = ("key", "scope_id")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("key", "scope")
    fieldsets = (
        (
            _("Setting"),
            {"fields": ("key", "scope", "scope_id", "tenant", "value")},
        ),
        (
            _("Metadata"),
            {
                "fields": ("updated_by", "public_id", "created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )

    @display(description=_("Scope"))
    def scope_badge(self, obj: SettingValue) -> str:
        colours = {
            "system": "#6b7280",
            "tenant": "#3b82f6",
            "org": "#f59e0b",
            "module": "#8b5cf6",
            "user": "#22c55e",
        }
        colour = colours.get(obj.scope, "#6b7280")
        return format_html(
            '<span style="background:{};color:#fff;padding:2px 8px;border-radius:4px;font-size:11px">{}</span>',
            colour,
            obj.scope,
        )

    @display(description=_("Value"))
    def value_preview(self, obj: SettingValue) -> str:
        text = str(obj.value)
        return text[:60] + "…" if len(text) > 60 else text
