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

from users.forms import CustomUserCreationForm, CustomUserChangeForm
from .models import User, SchoolClass, Role, UserRole, UserSetting, License, UserData, Team


class SchoolClassInline(admin.TabularInline):
    model = SchoolClass.users.through
    extra = 1


class RoleInline(admin.TabularInline):
    model = UserRole
    extra = 1


@admin.register(SchoolClass)
class SchoolClassAdmin(admin.ModelAdmin):
    list_display = ('name', 'code', 'user_list', 'is_deleted')

    inlines = [
        SchoolClassInline
    ]

    search_fields = ['name', 'users__username']

    def user_list(self, obj):
        return ', '.join([s.username for s in obj.users.all()])


@admin.register(Role)
class SchoolRoleAdmin(admin.ModelAdmin):
    list_display = ('name',)
    list_filter = ('name',)


@admin.register(UserRole)
class UserSchoolRoleAdmin(admin.ModelAdmin):
    list_display = ('user', 'role')
    # list_filter = ('role__school',)
    readonly_fields = []
    # search_fields = ('user__email', 'user__username')


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = User
    list_display = ('username', 'first_name', 'last_name', 'school_classes_list', 'is_superuser', 'hep_id')
    list_filter = ('school_classes', 'is_superuser')
    ordering = ['pk']
    search_fields = ('username', 'first_name', 'last_name')
    autocomplete_fields = ('team',)

    inlines = [
        SchoolClassInline,
        RoleInline,
    ]

    def school_classes_list(self, obj):
        return ', '.join([s.name for s in obj.school_classes.all()])

    # fieldsets = UserAdmin.fieldsets + (
    #     (None, {'fields': ('school_classes',)}),
    # )


admin.site.register(User, CustomUserAdmin)


@admin.register(UserSetting)
class UserSettingAdmin(admin.ModelAdmin):
    list_display = ('user', 'selected_class')
    raw_id_fields = ('user', 'selected_class')


@admin.register(License)
class LicenseAdmin(admin.ModelAdmin):
    list_display = ('licensee', 'for_role', 'expire_date', 'isbn', 'hep_created_at')
    list_filter = ('licensee', 'expire_date')
    raw_id_fields = ('licensee',)


@admin.register(UserData)
class UserDataAdmin(admin.ModelAdmin):
    list_display = ('user', 'accepted_terms')
    list_filter = ('accepted_terms',)
    raw_id_fields = ('user',)


@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
    list_display = ('name', 'creator', 'member_list',)
    readonly_fields = ('member_list',)
    search_fields = ('name', 'creator__first_name', 'creator__last_name')

    def member_list(self, obj):
        return ', '.join([member.full_name for member in obj.members.all()])
