from django import forms
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

from .access import all_columns, visible_schools, allowed_columns
from .models import AccessProfile, AccessRule, School

User = get_user_model()


class ProfileForm(forms.ModelForm):
    visible_columns = forms.MultipleChoiceField(
        required=False, widget=forms.CheckboxSelectMultiple, label="Columns this user can see",
        help_text="Leave all unticked for the basic set (code, district, municipality, ward, "
                  "type, total students). School name is always shown.")

    class Meta:
        model = AccessProfile
        fields = ["visible_columns", "can_export", "crm_access", "crm_can_assign"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["visible_columns"].choices = [(c, c) for c in all_columns()]


class AccessProfileInline(admin.StackedInline):
    model = AccessProfile
    form = ProfileForm
    can_delete = False
    verbose_name = "What this user may see and download"
    verbose_name_plural = "What this user may see and download"


class AccessRuleInline(admin.StackedInline):
    model = AccessRule
    extra = 1
    verbose_name = "Sharing rule"
    verbose_name_plural = ("Sharing rules - the user sees schools matching ANY rule below. "
                           "Within a rule, every filled box must match. A rule with nothing "
                           "filled in shares ALL schools. No rules = no data.")
    fields = ("label", "active", "districts", "municipalities", "school_types",
              ("min_students", "max_students"), ("min_up_to_class", "max_up_to_class"))


admin.site.unregister(User)


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    inlines = [AccessProfileInline, AccessRuleInline]
    list_display = ("username", "is_active", "is_superuser", "rules_summary", "schools_visible")
    readonly_fields = BaseUserAdmin.readonly_fields + ("access_preview",)
    fieldsets = BaseUserAdmin.fieldsets + (("Access preview", {"fields": ("access_preview",)}),)

    @admin.display(description="Rules")
    def rules_summary(self, user):
        if user.is_superuser:
            return "Admin: everything"
        rules = [r for r in user.access_rules.all() if r.active]
        return " | ".join(r.describe() for r in rules) or "none (sees nothing)"

    @admin.display(description="Schools visible")
    def schools_visible(self, user):
        return visible_schools(user).count()

    @admin.display(description="What this user sees right now")
    def access_preview(self, user):
        if not user.pk:
            return "Save the user first."
        qs = visible_schools(user)
        return (f"{qs.count()} schools in {qs.values('district_name').distinct().count()} "
                f"district(s), {len(allowed_columns(user))} columns. "
                f"(Save after changing rules to refresh.)")


@admin.register(School)
class SchoolAdmin(admin.ModelAdmin):
    list_display = ("name", "district_name", "municipality", "school_type", "total_students")
    list_filter = ("district_name", "school_type")
    search_fields = ("name", "municipality", "organization_id")
    list_per_page = 50
    fields = ("organization_id", "name", "district_id", "district_name", "municipality",
              "school_type", "total_students", "up_to_class", "data")
    readonly_fields = ()

    def has_add_permission(self, request):
        return True

    def has_change_permission(self, request, obj=None):
        return True

    def has_delete_permission(self, request, obj=None):
        return True
