from django.contrib import admin
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import Group, Permission

from .models import (
    Bilan, CercleScolaire, Contact, Document, Famille, Formation, GroupInfo,
    Intervenant, LibellePrestation, Personne, Prestation, Rapport, Region, Role,
    Service, Suivi, Utilisateur
)


class TypePrestationFilter(admin.SimpleListFilter):
    title = 'Prest. famil./générales'
    parameter_name = 'prest'
    default_value = None

    def lookups(self, request, model_admin):
        return (
            ('fam', 'Familiales'),
            ('gen', 'Générales'),
        )

    def queryset(self, request, queryset):
        value = self.value()
        if value == 'fam':
            return queryset.filter(famille__isnull=False).order_by('famille__nom')
        elif value == 'gen':
            return queryset.filter(famille__isnull=True).order_by('-date_prestation')
        return queryset


class RegionFilter(admin.SimpleListFilter):
    title = 'Région'
    parameter_name = 'region'

    def lookups(self, request, model_admin):
        typ = model_admin.model._meta.app_label
        kwargs = {f"{typ}": True}
        return [(reg.pk, reg.nom) for reg in Region.objects.filter(**kwargs)]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(region_id=self.value())
        return queryset


class DocumentInline(admin.TabularInline):
    model = Document
    extra = 1


class PersonneInLine(admin.StackedInline):
    model = Personne
    exclude = ('reseaux', 'remarque')
    extra = 1


@admin.register(Personne)
class PersonneAdmin(admin.ModelAdmin):
    list_display = ('nom_prenom', 'adresse')
    search_fields = ('nom', 'prenom')


@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
    list_display = ('nom', 'prenom', 'service', 'roles_display', 'est_actif')
    list_filter = ('service', 'est_actif')
    search_fields = ('nom', 'prenom', 'service__sigle')

    def roles_display(self, contact):
        return contact.roles_str(sep=' / ')
    roles_display.short_description = 'Rôles'


@admin.register(Famille)
class FamilleAdmin(admin.ModelAdmin):
    list_display = ('nom', 'npa', 'localite', 'get_region')
    list_filter = (RegionFilter,)
    inlines = [PersonneInLine, DocumentInline]
    ordering = ('nom',)
    search_fields = ('nom', 'localite')

    def get_region(self, obj):
        return obj.region.nom if obj.region else None
    get_region.short_description = 'Région'

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'region':
            app_label = self.model._meta.app_label
            param = {f"{app_label}": True}
            kwargs['queryset'] = Region.objects.filter(**param)
            kwargs['label'] = 'Région'
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(Formation)
class FormationAdmin(admin.ModelAdmin):
    list_display = ('personne', 'statut')
    search_fields = ('personne__nom',)
    ordering = ('personne__nom',)


class UtilisateurChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = Utilisateur


@admin.register(Utilisateur)
class UtilisateurAdmin(UserAdmin):
    form = UtilisateurChangeForm
    list_display = [
        'nom', 'prenom', 'sigle', 'tel_prof', 'tel_prive', 'email',
        'taux_activite', 'is_active', 'last_login'
    ]
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': (
            'sigle', 'prenom', 'nom', 'rue', 'npa', 'localite',
            'tel_prof', 'tel_prive', 'service', 'taux_activite'
        )}),
    )


admin.site.unregister(Group)


class GroupInfoInline(admin.StackedInline):
    model = GroupInfo


@admin.register(Group)
class GroupAdmin(GroupAdmin):
    inlines = [GroupInfoInline]


@admin.register(Region)
class RegionAdmin(admin.ModelAdmin):
    list_display = ['nom']


@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
    list_display = ['nom', 'est_famille', 'est_intervenant', 'est_editeur']


@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
    list_display = ['sigle', 'nom_complet']


@admin.register(LibellePrestation)
class LibellePrestationAdmin(admin.ModelAdmin):
    list_display = ['code', 'nom']


@admin.register(Permission)
class PermissionAdmin(admin.ModelAdmin):
    search_fields = ['name', 'codename']


@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('famille', 'titre')
    search_fields = ('famille__nom',)
    ordering = ('famille__nom',)


@admin.register(Suivi)
class SuiviAdmin(admin.ModelAdmin):
    list_display = ('famille', 'equipe', 'etape')
    list_filter = ('equipe',)
    ordering = ('famille__nom',)
    search_fields = ('famille__nom',)


@admin.register(Intervenant)
class IntervenantAdmin(admin.ModelAdmin):
    list_display = ('intervenant', 'famille', 'role', 'date_debut', 'date_fin', 'fin_suivi')
    list_filter = ('role',)

    def famille(self, obj):
        return obj.suivi.famille

    def fin_suivi(self, obj):
        return obj.suivi.date_fin_suivi


@admin.register(Prestation)
class PrestationAdmin(admin.ModelAdmin):
    list_display = ('lib_prestation', 'date_prestation', 'duree', 'auteur')
    list_filter = (TypePrestationFilter,)
    search_fields = ('famille__nom', 'texte')


admin.site.register(Bilan)
admin.site.register(Rapport)
admin.site.register(CercleScolaire)
