import datetime
from zoneinfo import ZoneInfo

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from beesgospel.models import (
    Agenda, Chant, ChantDoc, ConcertItem, Document, Membre, User
)


@admin.action(description="Générer répétition des 3 prochains mois")
def gen_repets(modeladmin, request, queryset):
    next_wedn = datetime.date.today()
    while next_wedn.isoweekday() != 3:
        next_wedn += datetime.timedelta(days=1)
    for i in range(12):
        if not Agenda.objects.filter(
            statut=Agenda.Statuts.REPETITION, date_heure__date=next_wedn
        ).exists():
            Agenda.objects.create(
                titre="Répétition", lieu="Temple Saint-Jean",
                date_heure=datetime.datetime.combine(
                    next_wedn, datetime.time(18, 30), tzinfo=ZoneInfo("Europe/Zurich")
                ),
                statut=Agenda.Statuts.REPETITION,
            )
        next_wedn += datetime.timedelta(days=7)


class ConcertItemInline(admin.TabularInline):
    model = ConcertItem
    extra = 0


@admin.register(Agenda)
class AgendaAdmin(admin.ModelAdmin):
    list_display = ["titre", "lieu", "date_heure", "statut"]
    ordering = ["-date_heure"]
    search_fields = ["titre", "lieu"]
    date_hierarchy = "date_heure"
    actions = [gen_repets]
    inlines = [ConcertItemInline]


@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    list_display = ["titre", "quand", "categorie", "prive"]
    list_filter = ["categorie"]
    ordering = ["-quand"]


@admin.register(Membre)
class MembreAdmin(admin.ModelAdmin):
    list_display = ["nom", "prenom", "localite", "user__email", "date_naissance"]
    ordering = ["nom"]


@admin.register(Chant)
class ChantAdmin(admin.ModelAdmin):
    list_display = ["titre", "particularite", "statut"]
    list_filter = ["statut"]
    search_fields = ["titre"]
    ordering = ["titre"]


@admin.register(ChantDoc)
class ChantDocAdmin(admin.ModelAdmin):
    list_display = ["titre", "chant", "fichier", "lien"]


@admin.register(User)
class UserAdmin(UserAdmin):
    list_display = ["email", "is_active", "is_staff", "last_login"]
    search_fields = ["email"]
    ordering = ["email"]
    fieldsets = (
        (None, {"fields": ("email", "password",)}),
        (
            "Permissions",
            {
                "fields": (
                    "is_active",
                    "is_staff",
                    "is_superuser",
                    "groups",
                    "user_permissions",
                ),
            },
        ),
        ("Important dates", {"fields": ("last_login", "date_joined")}),
    )
    add_fieldsets = (
        (
            None,
            {
                "classes": ("wide",),
                "fields": ("email", "usable_password", "password1", "password2"),
            },
        ),
    )
