"""
Accounts admin
"""
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import UserChangeForm as BaseUserChangeForm
from django.utils.translation import gettext_lazy as _

from .models import Role, User


class UserChangeForm(BaseUserChangeForm):
    """Custom user change form that handles nullable username field."""

    # Override username field to use a regular CharField that handles None
    username = forms.CharField(
        max_length=150,
        required=False,
        help_text=_('Optional. 150 characters or fewer.'),
    )

    class Meta(BaseUserChangeForm.Meta):
        model = User


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    """Custom User admin"""
    form = UserChangeForm

    list_display = ['email', 'username', 'first_name', 'last_name', 'hospital', 'department', 'is_active', 'is_staff']
    list_filter = ['is_active', 'is_staff', 'is_superuser', 'groups', 'hospital', 'department']
    search_fields = ['email', 'username', 'first_name', 'last_name', 'employee_id']
    ordering = ['-date_joined']
    
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'username', 'phone', 'employee_id')}),
        (_('Organization'), {'fields': ('hospital', 'department')}),
        (_('Profile'), {'fields': ('avatar', 'bio', 'language')}),
        (_('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', 'password1', 'password2'),
        }),
    )
    
    readonly_fields = ['date_joined', 'last_login', 'created_at', 'updated_at']
    
    def get_readonly_fields(self, request, obj=None):
        """Make username readonly for existing users since we use email for auth"""
        if obj:
            return self.readonly_fields + ['username']
        return self.readonly_fields

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('hospital', 'department')


@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
    """Role admin"""
    list_display = ['display_name', 'name', 'level', 'group', 'created_at']
    list_filter = ['level', 'name']
    search_fields = ['name', 'display_name', 'description']
    ordering = ['-level', 'name']
    
    fieldsets = (
        (None, {'fields': ('name', 'display_name', 'description')}),
        ('Configuration', {'fields': ('group', 'level', 'permissions')}),
        ('Metadata', {'fields': ('created_at', 'updated_at')}),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    filter_horizontal = ['permissions']
