from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .models import CustomUser, UserGroup

@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    """Admin configuration for CustomUser model"""
    
    list_display = ('username', 'email', 'first_name', 'last_name', 'user_type', 
                   'department', 'employee_id', 'is_active', 'date_joined')
    list_filter = ('user_type', 'department', 'is_active', 'date_joined')
    search_fields = ('username', 'first_name', 'last_name', 'email', 'employee_id')
    ordering = ('username',)
    
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'phone', 
                                       'department', 'employee_id', 'profile_picture')}),
        (_('Permissions'), {'fields': ('user_type', 'is_active', 'is_staff', 'is_superuser',
                                     'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2', 'email', 'first_name', 
                      'last_name', 'user_type', 'department', 'employee_id'),
        }),
    )
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related()

@admin.register(UserGroup)
class UserGroupAdmin(admin.ModelAdmin):
    """Admin configuration for UserGroup model"""
    
    list_display = ('name', 'description', 'user_count', 'created_at', 'updated_at')
    list_filter = ('created_at', 'updated_at')
    search_fields = ('name', 'description')
    ordering = ('name',)
    
    fieldsets = (
        (None, {'fields': ('name', 'description')}),
        (_('Users'), {'fields': ('users',)}),
        (_('Permissions'), {'fields': ('permissions',)}),
    )
    
    filter_horizontal = ('users',)
    
    def user_count(self, obj):
        return obj.users.count()
    user_count.short_description = 'Number of Users'
