from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import authenticate
from .models import User
from django.db.models import Q

# Formular de register
class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = User
        fields = ('username', 'email')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Labels
        self.fields['username'].label = "Utilizator"
        self.fields['email'].label = "Email"
        self.fields['password1'].label = "Parolă"
        self.fields['password2'].label = "Confirmă parola"

        # Help texts
        self.fields['username'].help_text = ""
        self.fields['email'].help_text = ""
        self.fields['password1'].help_text = (
            "Parola trebuie să aibă minim 8 caractere, "
            "să conțină litere mari, mici și cifre."
        )
        self.fields['password2'].help_text = "Reintrodu parola pentru confirmare."

        # Required
        for field in self.fields.values():
            field.required = True

    def clean_email(self):
        email = self.cleaned_data['email'].lower().strip()  # normalize
        # Verifică dacă emailul există deja sau este folosit ca username
        if User.objects.filter(Q(email__iexact=email) | Q(username__iexact=email)).exists():
            raise forms.ValidationError("Acest email este deja folosit.")
        return email

    def clean_username(self):
        username = self.cleaned_data['username'].strip()  # normalize
        # Verifică dacă username există deja sau este folosit ca email
        if User.objects.filter(Q(username__iexact=username) | Q(email__iexact=username)).exists():
            raise forms.ValidationError("Acest nume este deja folosit.")
        return username
    
#formular update profile
class UpdateProfileForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)
        self.fields['username'].label = "Utilizator"
        self.fields['email'].label = "Email"
        self.fields['username'].required = True
        self.fields['email'].required = True
        
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exclude(pk=self.instance.pk).exists():
            raise forms.ValidationError("Acest email este deja folosit.")
        return email
    
    def clean_username(self):
        username = self.cleaned_data['username']

        if User.objects.filter(username=username).exclude(pk=self.user.pk).exists():
            raise forms.ValidationError("Acest username este deja folosit de alt utilizator.")
        return username
    

class CustomAuthenticationForm(AuthenticationForm):
    username = forms.CharField(
        label="Utilizator sau email",
        widget=forms.TextInput(attrs={"autofocus": True})
    )
    password = forms.CharField(label="Parolă", widget=forms.PasswordInput)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            # încercăm autentificare clasică
            self.user_cache = authenticate(self.request, username=username, password=password)

            if self.user_cache is None:
                # dacă nu a mers cu username, încercăm cu email
                try:
                    user = User.objects.get(email__iexact=username)
                    self.user_cache = authenticate(self.request, username=user.username, password=password)
                except User.DoesNotExist:
                    self.user_cache = None

            if self.user_cache is None:
                self.add_error('password', "Utilizator sau parolă incorect.")
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
