from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import PasswordChangeView
from django.core.exceptions import ValidationError
from django.forms import CharField
from django.forms.models import ModelForm
from django.forms.widgets import PasswordInput


class LoginForm(AuthenticationForm):
    field_order = ['username', 'password']
    class Meta:
        model = get_user_model()


class RegisterForm(ModelForm):
    password1 = CharField(label='Password', widget=PasswordInput)
    password2 = CharField(label='Confirm Password', widget=PasswordInput)

    field_order = ['username', 'email', 'password1', 'password2', 'phone_number', 'company', 'line', 'user_type', 'company_permissions', 'employee_permissions', 'is_active']

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'password1', 'password2', 'phone_number', 'company', 'line', 'user_type', 'company_permissions', 'employee_permissions', 'is_active']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].widget.attrs.update({'autocomplete': 'new-password'})
        self.fields['password2'].widget.attrs.update({'autocomplete': 'new-password'})
        self.fields['user_type'].widget.attrs['readonly'] = True
        self.fields['company_permissions'].widget.attrs['disabled'] = True
        self.fields['employee_permissions'].widget.attrs['disabled'] = True

        if self.data.get('user_type') in ( 'EM', 'BS'):
            self.fields['company_permissions'].required = False
        if self.data.get('user_type') in ('CL', 'CA', 'BS'):
            self.fields['company_permissions'].required = False

    def clean(self):
        cleaned_data = super().clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise ValidationError("Passwords don't match")
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

class UserEditForm(ModelForm):
    password1 = CharField(required=False, label='Password', widget=PasswordInput)
    password2 = CharField(required=False, label='Confirm Password', widget=PasswordInput)

    field_order = ['username', 'email', 'password1', 'password2', 'phone_number', 'company', 'line', 'user_type', 'company_permissions', 'employee_permissions', 'is_active']

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'password1', 'password2', 'phone_number', 'company', 'line', 'user_type', 'company_permissions', 'employee_permissions', 'is_active']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['user_type'].widget.attrs['readonly'] = True
        self.fields['company_permissions'].widget.attrs['disabled'] = True
        self.fields['employee_permissions'].widget.attrs['disabled'] = True

        if self.data.get('user_type') in ( 'EM', 'BS'):
            self.fields['company_permissions'].required = False
        if self.data.get('user_type') in ('CL', 'CA', 'BS'):
            self.fields['company_permissions'].required = False

    def clean(self):
        cleaned_data = super().clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise ValidationError("Passwords don't match")
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user


class UserChangePasswordForm(PasswordChangeView):
    old_password = CharField(widget=PasswordInput())
    new_password = CharField(widget=PasswordInput())
    confirm_password = CharField(widget=PasswordInput())