from django import forms
from django.utils.translation import gettext_lazy as _
from .models import Profile

# Email Validators
from django.core.exceptions import ValidationError
from django.core.validators import EmailValidator

class SignupForm(forms.Form):
    
    # Email
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control mt-2 w-100', 
            'placeholder': 'mycompany@example.com',
            'aria-label': 'Email'
        }),
        label="Email"
    )

    # Password1 (Password) - Make optional for social login
    password1 = forms.CharField(
        label='Password',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control mt-2 w-100', 
            'aria-label': 'Password'
        }),
        min_length=6,
        required=False  # Changed to False for social login
    )

    # Password2 (Confirm Password) - Make optional for social login
    password2 = forms.CharField(
        label='Confirm Password',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control mt-2 w-100', 
            'aria-label': 'Confirm Password'
        }),
        required=False  # Changed to False for social login
    )

    # Terms and Conditions (Checkbox)
    agreed_to_terms = forms.BooleanField(
        label="I agree to the Terms and Conditions",
        required=True,
        widget=forms.CheckboxInput(attrs={
            'class': 'form-check-input mt-2', 
            'aria-label': 'Agree to Terms'
        }),
    )

    # Hidden field to track social login
    social_login = forms.BooleanField(
        required=False,
        widget=forms.HiddenInput()
    )

    def __init__(self, *args, **kwargs):
        social_login = kwargs.pop('social_login', False)
        super().__init__(*args, **kwargs)
        self.fields['social_login'].initial = social_login
        
        # If social login, make email read-only and hide password fields
        if social_login:
            self.fields['email'].widget.attrs['readonly'] = True
            self.fields['email'].widget.attrs['class'] += ' bg-gray-100'
            self.fields['password1'].widget = forms.HiddenInput()
            self.fields['password2'].widget = forms.HiddenInput()

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and Profile.objects.filter(email=email).exists():
            raise ValidationError(_("This email is already registered."))
        return email

    def clean(self):
        cleaned_data = super().clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        agreed_to_terms = cleaned_data.get('agreed_to_terms')
        social_login = cleaned_data.get('social_login', False)

        # For manual registration, validate passwords
        if not social_login:
            # Password Matching
            if password1 and password2 and password1 != password2:
                self.add_error('password2', _('Passwords do not match.'))
            
            # Password Strength Validation
            if password1 and len(password1) < 6:
                self.add_error('password1', _('Password must be at least 6 characters long.'))
            
            # Require passwords for manual registration
            if not password1:
                self.add_error('password1', _('Password is required.'))
            if not password2:
                self.add_error('password2', _('Please confirm your password.'))

        # Terms and Conditions validation (required for both)
        if not agreed_to_terms:
            self.add_error('agreed_to_terms', _("You must agree to the terms and conditions to create an account."))
        
        return cleaned_data
