from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User, Role, SiteConfiguration


@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
    list_display = ['name', 'description']
    search_fields = ['name']


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    list_display = ['email', 'full_name', 'get_roles', 'department', 'is_active', 'joined_date']
    list_filter = ['roles', 'department', 'is_active']
    search_fields = ['email', 'full_name']
    ordering = ['full_name']

    def get_roles(self, obj):
        return ", ".join([r.name for r in obj.roles.all()])
    get_roles.short_description = 'Roles'

    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal Info', {'fields': ('full_name', 'profile_photo', 'joined_date')}),
        ('Role & Department', {'fields': ('roles', 'department')}),
        ('Salary', {'fields': ('salary_pkr', 'hourly_rate')}),
        ('Preferences', {'fields': ('theme_preference', 'email_notifications', 'force_password_change')}),
        ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'full_name', 'password1', 'password2', 'department', 'salary_pkr'),
        }),
    )

    readonly_fields = ['hourly_rate']

@admin.register(SiteConfiguration)
class SiteConfigurationAdmin(admin.ModelAdmin):
    list_display = ['site_name', 'tagline', 'updated_at']
    
    def has_add_permission(self, request):
        # Only allow one instance
        if self.model.objects.exists():
            return False
        return super().has_add_permission(request)

    def has_delete_permission(self, request, obj=None):
        return False
