from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import Group, Permission

from .models import User, UserRole, Department

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = User
        fields = ('email', 'first_name', 'last_name')

class CustomUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = User
        fields = '__all__'

@admin.register(Department)
class DepartmentAdmin(admin.ModelAdmin):
    list_display = ('name', 'parent', 'get_subdepartments_count', 'description')
    list_filter = ('parent',)
    search_fields = ('name', 'description')
    
    def get_subdepartments_count(self, obj):
        return obj.subdepartments.count()
    get_subdepartments_count.short_description = 'Subdepartments'

@admin.register(UserRole)
class UserRoleAdmin(admin.ModelAdmin):
    list_display = ('name', 'get_permissions_count')
    filter_horizontal = ('permissions',)
    
    def get_permissions_count(self, obj):
        return obj.permissions.count()
    get_permissions_count.short_description = 'Permissions Count'

@admin.register(User)
class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = User
    
    # List view configuration
    list_display = ('email', 'first_name', 'last_name', 'get_role_name', 'get_department_name', 'is_staff', 'is_active')
    list_filter = ('is_staff', 'is_active', 'role', 'department')
    search_fields = ('email', 'first_name', 'last_name')
    ordering = ('email',)
    
    # Custom methods for list display
    def get_role_name(self, obj):
        return obj.role.name if obj.role else None
    get_role_name.short_description = 'Role'
    get_role_name.admin_order_field = 'role__name'
    
    def get_department_name(self, obj):
        return obj.department.name if obj.department else None
    get_department_name.short_description = 'Department'
    get_department_name.admin_order_field = 'department__name'
    
    # Fieldsets for add/change forms
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        (_('Personal info'), {
            'fields': ('first_name', 'last_name', 'phone_number')
        }),
        (_('Role and Department'), {
            'fields': ('role', 'department')
        }),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {
            'fields': ('last_login', 'date_joined'),
            'classes': ('collapse',),
        }),
    )
    
    # Fields for add form
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': (
                'email', 'password1', 'password2', 'first_name', 'last_name',
                'role', 'department', 'phone_number', 'is_staff', 'is_active'
            )}
        ),
    )
    
    # Form handling
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # Make sure the department field is always available in the form
        if 'department' in form.base_fields:
            form.base_fields['department'].required = False
            form.base_fields['department'].queryset = Department.objects.all()
        return form
    search_fields = ('email', 'first_name', 'last_name', 'phone_number')
    ordering = ('email',)
    filter_horizontal = ('groups', 'user_permissions')
    
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # Superusers can see all users
        if request.user.is_superuser:
            return qs
        # Regular staff users can only see users in their department
        if request.user.is_staff and hasattr(request.user, 'department') and request.user.department:
            return qs.filter(department=request.user.department)
        # Default to empty queryset if no department is set
        return qs.none()
    
    def get_readonly_fields(self, request, obj=None):
        readonly_fields = []
        if obj:  # Editing an existing object
            readonly_fields.extend(['last_login', 'date_joined'])
            if not request.user.is_superuser:
                readonly_fields.extend(['is_superuser', 'user_permissions', 'groups', 'is_staff'])
        return super().get_readonly_fields(request, obj) + tuple(readonly_fields)

# Unregister default Group admin
admin.site.unregister(Group)
