"""
Forms for accounts app.
"""
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm
from .models import User


class UserRegistrationForm(UserCreationForm):
    """
    User registration form with referral code support.
    """
    email = forms.EmailField(
        required=True,
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Address'})
    )
    first_name = forms.CharField(
        max_length=30,
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'})
    )
    last_name = forms.CharField(
        max_length=30,
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'})
    )
    referrer_code = forms.CharField(
        max_length=20,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Referral Code (Optional)'})
    )
    
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Username'})
        self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Password'})
        self.fields['password2'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Confirm Password'})
    
    def clean_referrer_code(self):
        referral_code = self.cleaned_data.get('referrer_code')
        # If referral code is provided, validate it exists
        if referral_code:
            if not User.objects.filter(referral_code=referral_code).exists():
                raise forms.ValidationError("Invalid referral code")
        return referral_code


class UserProfileForm(forms.ModelForm):
    """
    User profile update form.
    """
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'phone', 'address', 'country', 'city', 'postal_code', 'date_of_birth', 'profile_image', 'bio')
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
            'address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'country': forms.TextInput(attrs={'class': 'form-control'}),
            'city': forms.TextInput(attrs={'class': 'form-control'}),
            'postal_code': forms.TextInput(attrs={'class': 'form-control'}),
            'date_of_birth': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'profile_image': forms.FileInput(attrs={'class': 'form-control'}),
            'bio': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
        }


class IdentityVerificationForm(forms.ModelForm):
    """
    Form for uploading ID verification documents.
    """
    class Meta:
        model = User
        fields = ('id_card_image', 'selfie_image')
        widgets = {
            'id_card_image': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'}),
            'selfie_image': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'}),
        }

    def clean(self):
        cleaned_data = super().clean()
        id_card = cleaned_data.get('id_card_image') or self.instance.id_card_image
        selfie = cleaned_data.get('selfie_image') or self.instance.selfie_image

        if not id_card:
            self.add_error('id_card_image', 'Please upload your ID card.')
        if not selfie:
            self.add_error('selfie_image', 'Please upload your selfie.')

        return cleaned_data


class CustomPasswordChangeForm(PasswordChangeForm):
    """
    Custom password change form with Bootstrap styling.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['old_password'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Current Password'})
        self.fields['new_password1'].widget.attrs.update({'class': 'form-control', 'placeholder': 'New Password'})
        self.fields['new_password2'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Confirm New Password'})
