from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.db import transaction
from django_countries.fields import CountryField
from django_countries.widgets import CountrySelectWidget
from .models import UserProfile, GivingCircle

class UserProfileForm(UserCreationForm):
    username = forms.CharField(
        max_length=150,
        label="Nom d'utilisateur :",
        widget=forms.TextInput(attrs={'autocomplete': 'username'})
    )
    email = forms.EmailField(
        label="E-mail :",
        widget=forms.EmailInput(attrs={'autocomplete': 'email'})
    )
    first_name = forms.CharField(
        max_length=150,
        label="Prénom :",
        widget=forms.TextInput(attrs={'autocomplete': 'given-name'})
    )
    last_name = forms.CharField(
        max_length=150,
        label="Nom :",
        widget=forms.TextInput(attrs={'autocomplete': 'family-name'})
    )
    phone_number = forms.CharField(
        max_length=20,
        label="Numéro de téléphone (optionnel) :",
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '+33 6 12 34 56 78', 'autocomplete': 'tel'})
    )
    
    # New fields for enhanced signup
    country = CountryField(blank_label='Sélectionnez un pays').formfield(
        widget=CountrySelectWidget(attrs={'class': 'form-control', 'autocomplete': 'country'}),
        label="Pays :",
        required=False
    )
    giving_circle = forms.ModelChoiceField(
        queryset=GivingCircle.objects.all(),
        label="Cercle de donateurs (mensuel) :",
        required=False,
        empty_label="-- Choisir un Pack Parrain --",
        widget=forms.Select(attrs={'class': 'form-control', 'autocomplete': 'off'})
    )
    referral_source = forms.ChoiceField(
        choices=[('', '-- Sélectionnez --')] + UserProfile.REFERRAL_CHOICES,
        label="Comment avez-vous connu la plateforme ?",
        required=False,
        widget=forms.Select(attrs={'class': 'form-control', 'autocomplete': 'off'})
    )
    referral_details = forms.CharField(
        max_length=200,
        label="Précisions (optionnel) :",
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Par exemple: nom d\'un ami, nom du réseau social, etc.', 'autocomplete': 'off'})
    )
    
    # Subscription preferences
    monthly_donation_subscription = forms.BooleanField(
        label="Je souscris pour un don mensuel",
        required=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )
    newsletter_subscription = forms.BooleanField(
        label="J'accepte de recevoir des newsletters mensuels",
        required=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )
    whatsapp_group_subscription = forms.BooleanField(
        label="J'accepte d'intégrer le groupe WhatsApp de Sympathisants",
        required=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Add autocomplete attributes to password fields from UserCreationForm
        self.fields['password1'].widget.attrs.update({'autocomplete': 'new-password'})
        self.fields['password2'].widget.attrs.update({'autocomplete': 'new-password'})

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
        labels = {
            'username': "Nom d'utilisateur :",
        }

    def clean_username(self):
        """Validate that username is unique (case-insensitive)"""
        username = self.cleaned_data.get('username')
        if username and User.objects.filter(username__iexact=username).exists():
            raise forms.ValidationError("Ce nom d'utilisateur est déjà utilisé. Veuillez en choisir un autre.")
        return username

    def clean_email(self):
        """Validate that email is unique (case-insensitive)"""
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email__iexact=email).exists():
            raise forms.ValidationError("Cette adresse e-mail est déjà utilisée. Veuillez en utiliser une autre.")
        return email

    @transaction.atomic
    def save(self, commit=True):
        """
        Save user and profile in atomic transaction.
        If any error occurs, all changes are rolled back.
        """
        # Create user object but don't save to database yet
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        if commit:
            # Save user to database (within transaction)
            user.save()
            
            # Create user profile (within same transaction)
            # If this fails, user creation will be rolled back
            try:
                profile = UserProfile.objects.create(
                    user=user,
                    phone_number=self.cleaned_data.get('phone_number'),
                    country=self.cleaned_data.get('country'),
                    giving_circle=self.cleaned_data.get('giving_circle'),
                    referral_source=self.cleaned_data.get('referral_source'),
                    referral_details=self.cleaned_data.get('referral_details'),
                    monthly_donation_subscription=self.cleaned_data.get('monthly_donation_subscription', False),
                    newsletter_subscription=self.cleaned_data.get('newsletter_subscription', False),
                    whatsapp_group_subscription=self.cleaned_data.get('whatsapp_group_subscription', False)
                )
                profile.add_role('sponsor')
            except Exception as e:
                # If profile creation fails, transaction will rollback user creation
                raise forms.ValidationError(f"Erreur lors de la création du profil: {str(e)}")

        return user

