# accounts/admin.py
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.utils.html import format_html
from .models import CustomUser, AuditLog


@admin.register(AuditLog)
class AuditLogAdmin(admin.ModelAdmin):
    list_display = ('id', 'company', 'user', 'action', 'timestamp', 'ip_address')
    list_filter = ('company', 'action', 'timestamp')
    search_fields = ('target', 'user__username', 'company__name')
    readonly_fields = ('timestamp',)
    ordering = ('company', '-timestamp')


# ── Custom forms that declare pin_raw as a real form field ──────────────────

class CustomUserChangeForm(UserChangeForm):
    pin_raw = forms.CharField(
        label='Set new PIN',
        required=False,
        max_length=20,
        widget=forms.PasswordInput(
            attrs={'autocomplete': 'new-password', 'placeholder': 'Leave blank to keep existing PIN'}
        ),
        help_text='Enter digits only (4–8 digits). Leave blank to keep the current PIN unchanged.',
    )

    class Meta(UserChangeForm.Meta):
        model = CustomUser


class CustomUserCreationForm(UserCreationForm):
    pin_raw = forms.CharField(
        label='PIN (optional)',
        required=False,
        max_length=20,
        widget=forms.PasswordInput(
            attrs={'autocomplete': 'new-password', 'placeholder': 'Optional 4–8 digit PIN'}
        ),
        help_text='Enter digits only.',
    )

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'company', 'role', 'phone', 'profile_picture', 'branch')

# ── Admin class ─────────────────────────────────────────────────────────────

@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    form     = CustomUserChangeForm
    add_form = CustomUserCreationForm

    list_display = ('username', 'email', 'first_name', 'last_name', 'role', 'pin_status', 'is_active')
    list_filter  = ('role', 'is_active', 'date_joined')

    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('Personal Info', {'fields': ('first_name', 'last_name', 'email')}),
        ('Role & Profile', {'fields': ('company', 'branch', 'role', 'phone', 'profile_picture')}),
        ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
        ('Security PIN', {
            'description': (
                'Enter a 4–8 digit PIN to set it for this user. '
                'Leave blank to keep the existing PIN unchanged. '
                'The PIN is stored as a secure hash — you cannot view it here.'
            ),
            'fields': ('pin_raw',),
        }),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': (
                'username', 'password1', 'password2', 
                'company', 'branch', 'role', 'phone', 'profile_picture'
            ),
        }),
        ('Security PIN', {'description': 'Optional 4–8 digit PIN.', 'fields': ('pin_raw',)}),
    )

    def save_model(self, request, obj, form, change):
        raw_pin = form.cleaned_data.get('pin_raw', '').strip()
        if raw_pin:
            obj.set_pin(raw_pin)
        super().save_model(request, obj, form, change)

    @admin.display(description='PIN Set?')
    def pin_status(self, obj):
        if obj.pin_hash:
            return format_html('<span style="color:green;font-weight:bold;">&#10003; PIN set</span>')
        return format_html('<span style="color:#aaa;">No PIN</span>')