from django import forms
from django.core import validators

from module_iam.models import IAmPrincipal
from module_project import constants


class LoginForm(forms.Form):
    email = forms.EmailField(
        max_length=254,
        widget=forms.TextInput(attrs={"autofocus": True}),
        label="Email",
    )
    password = forms.CharField(
        label="Password",
        strip=False,
        widget=forms.PasswordInput()
    )


class UserForm(forms.ModelForm):
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={"autocomplete": "off"}),
        validators=[
            validators.MinLengthValidator(
                limit_value=6, message="Password must be at least 6 characters long. "
            )
        ],
    )
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={"autocomplete": "off"})
    )

    class Meta:
        model = IAmPrincipal
        fields = [
            "first_name",
            "email",
            "password",
            "confirm_password",
        ]
        labels = {
            "first_name": "Name",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        instance = kwargs.get("instance")
        if instance and instance.pk:
            # Remove password and confirm_password fields if instance exists (update action)
            self.fields.pop("password")
            self.fields.pop("confirm_password")
            # Make email field readonly
            self.fields["email"].widget.attrs["readonly"] = True
    
    def clean_email(self):
        # Prevent email from being updated
        instance = self.instance
        if instance and instance.pk:
            return instance.email
        else:
            email = self.cleaned_data.get("email")
            if IAmPrincipal.objects.filter(email=email).exclude(pk=instance.pk).exists():
                raise forms.ValidationError("This email address is already in use.")
            return email

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        if password and confirm_password and password != confirm_password:
            self.add_error("confirm_password", "Passwords do not match.")
        return cleaned_data

    def save(self, commit=True):
        instance = super().save(commit=False)
        # Check if it's a new object (create action) or an existing one (update action)
        if not instance.pk:  # pk is None for new objects
            instance.username = self.cleaned_data["email"]
            instance.set_password(self.cleaned_data["password"])
        if commit:
            instance.save()
        return instance

