from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import FileExtensionValidator
from .models import User, CustomerProfile
from .countries import COUNTRIES


class CustomerRegistrationForm(UserCreationForm):
    
    customer_type = forms.ChoiceField(
        choices=CustomerProfile.CustomerType.choices,
        widget=forms.RadioSelect(attrs={'class': 'customer-type-radio'})
    )
    
    job_title = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Job Title'
        })
    )
    phone_number = forms.CharField(
        max_length=20,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Phone Number'
        })
    )
    
    company_name = forms.CharField(
        max_length=255,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Company Name'
        })
    )
    company_legal_name = forms.CharField(
        max_length=255,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Company Legal Name'
        })
    )
    company_email = forms.EmailField(
        required=False,
        widget=forms.EmailInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Company Email'
        })
    )
    vat_tax_number = forms.CharField(
        max_length=50,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'VAT/Tax Number'
        })
    )
    
    street_address = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Street Address'
        })
    )
    city = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'City'
        })
    )
    country = forms.ChoiceField(
        choices=COUNTRIES,
        initial='AE',
        widget=forms.Select(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500'
        })
    )
    state_province = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'State/Province'
        })
    )
    zip_code = forms.CharField(
        max_length=20,
        widget=forms.TextInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Zip Code'
        })
    )
    
    file_attrs = {'class': 'hidden', 'accept': '.pdf,.jpeg,.jpg,.png'}
    file_validators = [FileExtensionValidator(allowed_extensions=['pdf', 'jpeg', 'jpg', 'png'])]
    
    business_permit = forms.FileField(required=False, validators=file_validators, widget=forms.FileInput(attrs=file_attrs))
    commercial_trading_license = forms.FileField(required=False, validators=file_validators, widget=forms.FileInput(attrs=file_attrs))
    vat_registration_certificate = forms.FileField(required=False, validators=file_validators, widget=forms.FileInput(attrs=file_attrs))
    owner_passport_copy = forms.FileField(required=False, validators=file_validators, widget=forms.FileInput(attrs=file_attrs))
    national_id = forms.FileField(required=False, validators=file_validators, widget=forms.FileInput(attrs=file_attrs))
    
    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name', 'password1', 'password2']
        widgets = {
            'email': forms.EmailInput(attrs={
                'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
                'placeholder': 'Email'
            }),
            'first_name': forms.TextInput(attrs={
                'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
                'placeholder': 'First Name'
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
                'placeholder': 'Last Name'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].widget.attrs.update({
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Password'
        })
        self.fields['password2'].widget.attrs.update({
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Confirm Password'
        })
    
    def clean(self):
        cleaned_data = super().clean()
        customer_type = cleaned_data.get('customer_type')
        
        if customer_type == CustomerProfile.CustomerType.BUSINESS:
            required_fields = {
                'company_name': 'Company Name',
                'company_email': 'Company Email ID',
                'commercial_trading_license': 'Commercial/Trading License',
                'vat_registration_certificate': 'VAT Registration Certificate',
            }
            for field, label in required_fields.items():
                if not cleaned_data.get(field):
                    self.add_error(field, f'{label} is required for Business registration.')
            
            required_docs = {
                'owner_passport_copy': 'Owner Passport Copy',
                'national_id': 'National ID',
            }
            for field, label in required_docs.items():
                if not cleaned_data.get(field):
                    self.add_error(field, f'{label} is required.')
        
        return cleaned_data
    
    def save(self, commit=True):
        user = super().save(commit=False)
        user.username = self.cleaned_data['email']  
        if commit:
            user.save()
            CustomerProfile.objects.create(
                user=user,
                customer_type=self.cleaned_data['customer_type'],
                job_title=self.cleaned_data.get('job_title', ''),
                phone_number=self.cleaned_data['phone_number'],
                company_name=self.cleaned_data.get('company_name', ''),
                company_legal_name=self.cleaned_data.get('company_legal_name', ''),
                company_email=self.cleaned_data.get('company_email', ''),
                vat_tax_number=self.cleaned_data.get('vat_tax_number', ''),
                street_address=self.cleaned_data['street_address'],
                city=self.cleaned_data['city'],
                country=self.cleaned_data['country'],
                state_province=self.cleaned_data.get('state_province', ''),
                zip_code=self.cleaned_data['zip_code'],
                business_permit=self.cleaned_data.get('business_permit'),
                commercial_trading_license=self.cleaned_data.get('commercial_trading_license'),
                vat_registration_certificate=self.cleaned_data.get('vat_registration_certificate'),
                owner_passport_copy=self.cleaned_data.get('owner_passport_copy'),
                national_id=self.cleaned_data.get('national_id'),
            )
        return user


class CustomerLoginForm(forms.Form):
    
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Email'
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500',
            'placeholder': 'Password'
        })
    )
