from django import forms

from .models import AffiliateProfile, AffiliateResourceRequest
from django.core.exceptions import ValidationError
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import User
from common.choices import NATIONALITY_CHOICES, COUNTRY_CHOICES, LANGUAGE_CHOICES

class AffiliateUsernameChangeForm(forms.Form):
    new_username = forms.CharField(
        max_length=150,
        label="New Username",
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter new username'})
    )
    password = forms.CharField(
        label="Confirm Password",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Enter your current password'})
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

    def clean_new_username(self):
        new_username = self.cleaned_data.get('new_username')
        if User.objects.exclude(pk=self.user.pk).filter(username__iexact=new_username).exists():
            raise ValidationError("This username is already taken. Please choose another.")
        return new_username

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if not self.user.check_password(password):
            raise ValidationError("Incorrect password. Please try again.")
        return password

    def save(self):
        new_username = self.cleaned_data['new_username']
        self.user.username = new_username
        self.user.save()
        return self.user

class AffiliateProfileEditForm(forms.ModelForm):
    class Meta:
        model = AffiliateProfile
        fields = [
            'full_name',
            'phone',
            'whatsapp',
            'country',
            'bank_name',
            'bank_account_name',
            'bank_account_number',
            'bank_branch',
            'payout_notes',
        ]
        widgets = {
            'payout_notes': forms.Textarea(attrs={'rows': 3}),
        }
        help_texts = {
            'bank_account_number': 'Your account number (without spaces)',
            'payout_notes': 'Any special instructions for payouts',
        }

class AffiliateProfilePhotoForm(forms.ModelForm):
    class Meta:
        model = AffiliateProfile
        fields = ['profile_photo']
        widgets = {
            'profile_photo': forms.FileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'})
        }

class AffiliatePasswordResetForm(PasswordResetForm):
    """
    Only allows password reset emails for active users
    who have an AffiliateProfile.
    """

    def get_users(self, email):
        active_users = super().get_users(email)
        for user in active_users:
            if hasattr(user, 'affiliate_profile') and user.affiliate_profile.is_active:
                yield user

class AffiliateRegisterForm(forms.ModelForm):
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'Your email address'
        })
    )

    class Meta:
        model = AffiliateProfile
        fields = [
            'full_name',
            'email',
            'phone',
            'whatsapp',
            'country',
            'bank_name',
            'bank_account_name',
            'bank_account_number',
            'bank_branch',
            'payout_notes',
        ]

        widgets = {
            'full_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Your full name'
            }),
            'phone': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Phone number'
            }),
            'whatsapp': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'WhatsApp number'
            }),
            'country': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Country'
            }),
            'bank_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Bank name'
            }),
            'bank_account_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Account holder name'
            }),
            'bank_account_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Bank account number'
            }),
            'bank_branch': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Branch name'
            }),
            'payout_notes': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': 'Any payout instructions or notes'
            }),
        }

class AffiliateResourceRequestForm(forms.ModelForm):
    requested_languages = forms.MultipleChoiceField(
        choices=LANGUAGE_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        label="Select languages for your custom materials"
    )
    
    class Meta:
        model = AffiliateResourceRequest
        fields = ['requested_languages']
    
    def save(self, commit=True):
        instance = super().save(commit=False)
        if commit:
            instance.save()
            # if using JSONField, we store the list directly
            instance.requested_languages = self.cleaned_data['requested_languages']
            instance.save()
        return instance