"""
Django admin configuration for accounts app.
"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User


class VerificationRequestFilter(admin.SimpleListFilter):
    """
    Filter users by verification submission state.
    """
    title = 'verification request'
    parameter_name = 'verification_status'

    def lookups(self, request, model_admin):
        return (
            ('pending', 'Pending review'),
            ('verified', 'Verified'),
            ('not_submitted', 'Not submitted'),
        )

    def queryset(self, request, queryset):
        pending_queryset = queryset.filter(
            is_verified=False,
            id_card_image__isnull=False,
            selfie_image__isnull=False,
        ).exclude(id_card_image='').exclude(selfie_image='')

        if self.value() == 'pending':
            return pending_queryset
        if self.value() == 'verified':
            return queryset.filter(is_verified=True)
        if self.value() == 'not_submitted':
            return queryset.filter(is_verified=False).filter(id_card_image__isnull=True, selfie_image__isnull=True)
        return queryset


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    """
    Custom User Admin with Jazzmin styling.
    """
    list_display = (
        'username',
        'email',
        'first_name',
        'last_name',
        'verification_request_status',
        'is_verified',
        'is_staff',
        'is_active',
        'wallet_balance',
        'created_at',
    )
    list_filter = ('is_staff', 'is_active', 'is_superuser', 'is_verified', VerificationRequestFilter)
    search_fields = ('username', 'email', 'first_name', 'last_name', 'referral_code')
    ordering = ('-created_at',)
    
    fieldsets = BaseUserAdmin.fieldsets + (
        ('Referral Info', {'fields': ('referral_code', 'referred_by', 'wallet_balance', 'total_earnings', 'referral_earnings')}),
        ('Profile Info', {'fields': ('phone', 'address', 'country', 'city', 'postal_code', 'date_of_birth', 'profile_image', 'bio')}),
        ('Identity Verification', {'fields': ('id_card_image', 'selfie_image', 'is_verified')}),
        ('Status', {'fields': ('is_active_signal',)}),
    )
    
    add_fieldsets = BaseUserAdmin.add_fieldsets + (
        ('Referral Info', {'fields': ('referral_code',)}),
    )

    @admin.display(description='Verification Request')
    def verification_request_status(self, obj):
        if obj.is_verified:
            return 'Verified'
        if obj.has_submitted_verification:
            return 'Pending Review'
        return 'Not Submitted'
