from django import forms
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm

from .models import Role, User


class FablabsLoginForm(AuthenticationForm):
    username = forms.CharField(
        label="E-mail ou matricule",
        widget=forms.TextInput(attrs={"autofocus": True, "autocomplete": "username", "placeholder": "vous@fablabs.cm"}),
    )
    password = forms.CharField(
        label="Mot de passe",
        widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
    )

    error_messages = {
        "invalid_login": "Identifiants incorrects. Vérifiez votre e-mail ou matricule et votre mot de passe.",
        "inactive": "Ce compte est désactivé. Contactez votre administrateur.",
        "locked": "Trop de tentatives de connexion. Pour votre sécurité, réessayez dans 15 minutes "
                  "ou réinitialisez votre mot de passe.",
    }

    def clean(self):
        try:
            return super().clean()
        except forms.ValidationError:
            if getattr(self.request, "fm_login_locked", False):
                raise forms.ValidationError(self.error_messages["locked"], code="locked")
            raise


class ProfileForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["first_name", "last_name", "phone", "language", "theme"]
        labels = {"first_name": "Prénom", "last_name": "Nom", "phone": "Téléphone",
                  "language": "Langue", "theme": "Thème d'affichage"}


class UserCreateForm(forms.Form):
    email = forms.EmailField(label="E-mail")
    first_name = forms.CharField(label="Prénom", max_length=80)
    last_name = forms.CharField(label="Nom", max_length=80)
    matricule = forms.CharField(label="Matricule", max_length=32, required=False)
    phone = forms.CharField(label="Téléphone", max_length=32, required=False)
    role = forms.ModelChoiceField(label="Rôle", queryset=Role.objects.none())
    password = forms.CharField(label="Mot de passe provisoire", widget=forms.PasswordInput,
                               help_text="L'utilisateur devra le changer à sa première connexion.")

    def __init__(self, *args, actor=None, agency=None, **kwargs):
        super().__init__(*args, **kwargs)
        from .roles import assignable_roles
        self.fields["role"].queryset = assignable_roles(actor, agency) if actor else Role.objects.none()

    def clean_email(self):
        email = self.cleaned_data["email"].lower()
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("Un compte existe déjà avec cet e-mail.")
        return email

    def clean_matricule(self):
        matricule = self.cleaned_data.get("matricule", "").strip()
        if matricule and User.objects.filter(matricule__iexact=matricule).exists():
            raise forms.ValidationError("Ce matricule est déjà attribué.")
        return matricule

    def clean(self):
        data = super().clean()
        password = data.get("password")
        if password:
            from django.contrib.auth.password_validation import validate_password
            candidate = User(email=data.get("email", ""), first_name=data.get("first_name", ""),
                             last_name=data.get("last_name", ""))
            try:
                validate_password(password, candidate)
            except forms.ValidationError as exc:
                self.add_error("password", exc)
        return data
