from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import RegexValidator, FileExtensionValidator
from .models import User

class CustomUserCreationForm(UserCreationForm):
    """Form for user registration"""
    
    # Personal Details
    first_name = forms.CharField(
        max_length=150,
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter your first name'})
    )
    last_name = forms.CharField(
        max_length=150,
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter your last name'})
    )
    email = forms.EmailField(
        required=True,
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'youremail@gmail.com'})
    )
    phone_number = forms.CharField(
        max_length=15,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '0712345678'}),
        help_text="Format: 0712345678"
    )
    county = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your county'})
    )
    constituency = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your constituency'})
    )
    
    # Education Details
    institution = forms.CharField(
        max_length=200,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'University/College name'})
    )
    course = forms.CharField(
        max_length=200,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your course'})
    )
    registration_number = forms.CharField(
        max_length=50,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Registration number'})
    )
    
    # Document Uploads
    student_id = forms.ImageField(
        required=False,
        widget=forms.FileInput(attrs={
            'class': 'form-control',
            'accept': 'image/*',
            'onchange': 'previewImage(this, "studentIdPreview")'
        })
    )
    national_id = forms.FileField(
        required=False,
        widget=forms.FileInput(attrs={
            'class': 'form-control',
            'accept': '.pdf',
            'onchange': 'previewPDF(this, "nationalIdPreview")'
        })
    )
    
    # Password fields
    password1 = forms.CharField(
        label='Password',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Create a password'})
    )
    password2 = forms.CharField(
        label='Confirm Password',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm your password'})
    )
    
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'phone_number', 
                 'county', 'constituency', 'institution', 'course', 
                 'registration_number', 'student_id', 'national_id')
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Remove help texts
        for field in self.fields:
            self.fields[field].help_text = ''
    
    def clean_phone_number(self):
        phone = self.cleaned_data.get('phone_number')
        if phone:
            # Remove any spaces or dashes
            phone = phone.replace(' ', '').replace('-', '')
            
            # Validate format
            if not phone.startswith('0'):
                raise forms.ValidationError("Phone number must start with 0")
            if len(phone) != 10:
                raise forms.ValidationError("Phone number must be 10 digits")
            if not phone.isdigit():
                raise forms.ValidationError("Phone number must contain only digits")
        return phone
    
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError("A user with this email already exists.")
        return email
    
    def save(self, commit=True):
        user = super().save(commit=False)
        user.username = self.cleaned_data['email']  # Use email as username
        user.email = self.cleaned_data['email']
        
        if commit:
            user.save()
        return user

class CustomLoginForm(forms.Form):
    """Form for user login (supports email or phone)"""
    identifier = forms.CharField(
        label='Email or Phone Number',
        widget=forms.TextInput(attrs={
            'class': 'form-control login-identifier',
            'placeholder': 'youremail@gmail.com or 0712345678'
        })
    )
    password = forms.CharField(
        label='Password',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control login-password',
            'placeholder': 'Enter your password'
        })
    )
    
    def clean_identifier(self):
        identifier = self.cleaned_data.get('identifier')
        if not identifier:
            raise forms.ValidationError("This field is required.")
        return identifier