from django import forms
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError

User = get_user_model()

class UserProfileCreationForm(forms.ModelForm):
    """Form to create a user profile in the admin interface."""
    password1 = forms.CharField(
        label="Mot de passe",
        widget=forms.PasswordInput,
        required=False,
        help_text="Laissez vide, l'utilisateur définira son mot de passe après validation."
    )
    password2 = forms.CharField(
        label="Confirmer mot de passe",
        widget=forms.PasswordInput,
        required=False
    )

    class Meta:
        model = User
        fields = (
            "email",
            "first_name",
            "last_name",
            "speciality",
            "profile_image",
            "phone_number",
            "document",
        )

    def clean(self):
        cleaned_data = super().clean()
        p1 = cleaned_data.get("password1")
        p2 = cleaned_data.get("password2")
        if p1 or p2:
            if p1 != p2:
                raise ValidationError("Les mots de passe ne correspondent pas.")
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        p1 = self.cleaned_data.get("password1")
        if p1:
            user.set_password(p1)
        else:
            user.set_unusable_password()
        if commit:
            user.save()
        return user


class ModeratorUserCreationForm(forms.ModelForm):
    """Form for moderators: no password or permissions."""
    class Meta:
        model = User
        fields = [
            "email",
            "first_name",
            "last_name",
            "speciality",
            "phone_number",
            "document",
            "profile_image",
        ]

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_unusable_password()
        user.is_active = False
        if commit:
            user.save()
        return user