from django import forms
from django.contrib import admin
from django.contrib.auth.hashers import make_password
from django.utils.translation import gettext_lazy as _

from users.imports.admin import BaseModelAdmin as Parent
from users.models import UserModel

INITIAL_PASSWORD = '********'


class Form(forms.ModelForm):
    new_password = forms.CharField(
        required=False, initial=INITIAL_PASSWORD, label=' Password')

    class Meta:
        model = UserModel
        fields = [
            'new_password',
        ]


@admin.register(UserModel)
class UserModelAdmin(Parent):
    list_display = [
        'is_active',
        'account_verified',
        'username',
        'phone_number',
        'email_address',
        'id',
        'is_staff',
    ]
    list_display_links = [
        'is_active',
        'account_verified',
        'id',
        'username',
        'phone_number',
        'email_address',
        'is_staff',
    ]
    search_fields = [
        'id',
        'username',
        'phone_number',
        'email_address',
    ]
    list_filter = [
        'roles',
        'is_staff',
        'is_active',
        'is_superuser',
        'groups',
    ]
    readonly_fields = [
        'date_joined',
        'last_login',
        'account_verified',
    ]
    filter_horizontal = ['groups', 'user_permissions', 'roles']
    fieldsets = [
        (_('Info'), {
            'fields': [
                ('username', 'new_password',),

                ('phone_number', 'phone_number_verified',),
                ('email_address', 'email_address_verified',),
                'roles',

            ]}),
        (_('Config'), {
            'fields': [
                'account_verified',
                'is_active',
                'is_staff',
                'is_superuser',
                'date_joined',
                'last_login',
                'groups',
                'user_permissions',
            ]}),
    ]
    form = Form

    def save_model(self, request, obj, form, change):
        new_password = request.POST.get('new_password')

        if new_password and new_password != INITIAL_PASSWORD:
            hashed_password = make_password(new_password)
            obj.password = hashed_password
            obj.backup_password = hashed_password

        super().save_model(request, obj, form, change)
