from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group

from territories_dashboard_lib.commons.admin import AdminInfoMixin
from territories_dashboard_lib.website_lib.forms import (
    GlossaryItemAdminForm,
    LandingPageAdminForm,
    MainConfAdminForm,
    StaticPageAdminForm,
)
from territories_dashboard_lib.website_lib.models import (
    GlossaryItem,
    LandingPage,
    MainConf,
    NoticeBanner,
    StaticPage,
)
from territories_dashboard_lib.website_lib.utils import get_website_links


@admin.register(MainConf)
class MainConfAdmin(AdminInfoMixin, admin.ModelAdmin):
    admin_info = "Paramétrage de la configuration générale du site."
    form = MainConfAdminForm

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        links = ", ".join(get_website_links())
        form.base_fields["header_navigation"].help_text = (
            form.base_fields["header_navigation"].help_text
            + f"<br/><br/>---<br/><br/>Liens disponibles : {links}"
        )
        form.base_fields["footer_navigation"].help_text = (
            form.base_fields["footer_navigation"].help_text
            + f"<br/><br/>---<br/><br/>Liens disponibles : {links}"
        )
        return form


@admin.register(GlossaryItem)
class GlossaryItemAdmin(AdminInfoMixin, admin.ModelAdmin):
    admin_info = "Paramétrage de la page Lexique du site."
    form = GlossaryItemAdminForm


@admin.register(LandingPage)
class LandingPageAdminForm(AdminInfoMixin, admin.ModelAdmin):
    admin_info = "Paramétrage de la page d'accueil du site."
    form = LandingPageAdminForm


@admin.register(StaticPage)
class StaticPageAdminForm(AdminInfoMixin, admin.ModelAdmin):
    admin_info = "Paramétrage des pages statiques du site."
    form = StaticPageAdminForm


@admin.register(NoticeBanner)
class NoticeBannerAdmin(AdminInfoMixin, admin.ModelAdmin):
    admin_info = (
        "Paramétrage des bandeaux d'information à afficher sur les pages du site."
    )
    list_display = ("title", "created_at")


admin.site.unregister(Group)


class CustomUserAdmin(UserAdmin):
    def get_favorite_indicators(self, obj):
        names = obj.favorite_indicators.values_list("title", flat=True)
        return "\n ".join(names) if names else "-"

    get_favorite_indicators.short_description = "Indicateurs favoris"

    readonly_fields = UserAdmin.readonly_fields + ("get_favorite_indicators",)
    fieldsets = UserAdmin.fieldsets + (
        ("Indicateurs favoris", {"fields": ("get_favorite_indicators",)}),
    )


admin.site.unregister(get_user_model())
admin.site.register(get_user_model(), CustomUserAdmin)
