from django import forms
from .models import ServicePartnerProfile, ServicePartnerInterest

from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from common.choices import SRI_LANKA_CITY_CHOICES, SRI_LANKA_DISTRICT_CHOICES, COUNTRY_CHOICES
from django.contrib.auth.forms import PasswordResetForm
User = get_user_model()


class ServicePartnerPasswordResetForm(PasswordResetForm):
    """
    Only allows password reset emails for active users
    who have a ServicePartnerProfile.
    """

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

class ServicePartnerProfileEditForm(forms.ModelForm):
    class Meta:
        model = ServicePartnerProfile
        fields = [
            'service_type',
            'full_name',
            'display_name',
            'gender',
            'date_of_birth',
            'city',
            'district',
            'country',
            'address',

            'resume_or_bio_data',

            'short_intro',
            'about_me',
            'languages_spoken',
            'phone_number',
            'whatsapp_number',
            'email',
            'experience_summary',
            'skills',
            'education',
            'has_license',
            'passport_ready',
            'willing_to_relocate',
            'live_in_available',
            'part_time_available',
            'full_time_available',
        ]

        widgets = {
            'date_of_birth': forms.DateInput(attrs={'type': 'date'}),
            'city': forms.Select(),
            'district': forms.Select(),
            'country': forms.Select(),
            'address': forms.Textarea(attrs={'rows': 3}),
            'about_me': forms.Textarea(attrs={'rows': 4}),
            'experience_summary': forms.Textarea(attrs={'rows': 4}),
            'skills': forms.Textarea(attrs={'rows': 4}),
            'short_intro': forms.TextInput(attrs={'maxlength': 255}),
            'resume_or_bio_data': forms.FileInput(attrs={
                'accept': '.pdf,.doc,.docx',
            }),
        }

        labels = {
            'resume_or_bio_data': 'Resume / Biodata',
        }

        help_texts = {
            'resume_or_bio_data': 'Upload your resume, CV, or biodata document. PDF, DOC, or DOCX only.',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['city'].choices = [('', 'Select city')] + list(SRI_LANKA_CITY_CHOICES)
        self.fields['district'].choices = [('', 'Select district')] + list(SRI_LANKA_DISTRICT_CHOICES)
        self.fields['country'].choices = [('', 'Select country')] + list(COUNTRY_CHOICES)

        # Make resume optional
        self.fields['resume_or_bio_data'].required = False

        for field in self.fields.values():
            css = 'form-control'

            if isinstance(field.widget, forms.CheckboxInput):
                css = 'form-check-input'
            elif isinstance(field.widget, forms.Select):
                css = 'form-select'
            elif isinstance(field.widget, forms.FileInput):
                css = 'form-control'

            field.widget.attrs.setdefault('class', css)

    def clean_full_name(self):
        full_name = self.cleaned_data.get('full_name', '').strip()

        if not full_name:
            raise ValidationError("Full name is required.")

        return full_name

    def clean_email(self):
        email = self.cleaned_data['email'].strip().lower()

        qs = User.objects.filter(email__iexact=email)

        if self.instance.user:
            qs = qs.exclude(pk=self.instance.user.pk)

        if qs.exists():
            raise ValidationError("This email is already used by another account.")

        return email

    def save(self, commit=True):
        partner = super().save(commit=False)

        if partner.user:
            full_name = self.cleaned_data.get('full_name', '').strip()
            name_parts = full_name.split()

            partner.user.first_name = name_parts[0] if name_parts else ''
            partner.user.last_name = ' '.join(name_parts[1:]) if len(name_parts) > 1 else ''
            partner.user.email = self.cleaned_data['email']

            if commit:
                partner.user.save()

        if commit:
            partner.save()

        return partner


class ServicePartnerProfileImageForm(forms.ModelForm):
    class Meta:
        model = ServicePartnerProfile
        fields = ['profile_photo']

    def clean_profile_photo(self):
        image = self.cleaned_data.get('profile_photo')
        if not image:
            return image

        allowed_content_types = ['image/jpeg', 'image/png', 'image/webp']
        if hasattr(image, 'content_type') and image.content_type not in allowed_content_types:
            raise ValidationError("Only JPG, PNG, or WEBP images are allowed.")

        return image


class UsernameChangeForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username']

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

        for field in self.fields.values():
            css = 'form-control'
            if isinstance(field.widget, forms.CheckboxInput):
                css = 'form-check-input'
            field.widget.attrs.setdefault('class', css)

    def clean_username(self):
        username = self.cleaned_data['username'].strip()
        qs = User.objects.filter(username__iexact=username)
        if self.user:
            qs = qs.exclude(pk=self.user.pk)
        if qs.exists():
            raise ValidationError("This username is already taken.")
        return username

class ServicePartnerRegistrationForm(forms.ModelForm):
    class Meta:
        model = ServicePartnerProfile
        fields = [
            'service_type',
            'full_name',
            'display_name',
            'gender',
            'date_of_birth',
            'city',
            'district',
            'address',
            'profile_photo',
            'short_intro',
            'about_me',
            'languages_spoken',
            'phone_number',
            'whatsapp_number',
            'email',
            'experience_summary',
            'skills',
            'education',
            'has_license',
            'passport_ready',
            'willing_to_relocate',
            'live_in_available',
            'part_time_available',
            'full_time_available',
            'agreed_to_terms',
        ]
        widgets = {
            'date_of_birth': forms.DateInput(attrs={'type': 'date'}),
            'city': forms.Select(),
            'district': forms.Select(),
            'about_me': forms.Textarea(attrs={'rows': 4}),
            'experience_summary': forms.Textarea(attrs={'rows': 3}),
            'skills': forms.Textarea(attrs={'rows': 3}),
            'address': forms.Textarea(attrs={'rows': 3}),
        }
        labels = {
            'agreed_to_terms': "I agree to Ensolanka’s Terms & Conditions and Privacy Policy",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['city'].choices = [('', 'Select city')] + list(SRI_LANKA_CITY_CHOICES)
        self.fields['district'].choices = [('', 'Select district')] + list(SRI_LANKA_DISTRICT_CHOICES)

        for name, field in self.fields.items():
            if isinstance(field.widget, forms.CheckboxInput):
                field.widget.attrs.update({'class': 'form-check-input'})
            elif isinstance(field.widget, forms.Select):
                field.widget.attrs.update({'class': 'form-select'})
            elif isinstance(field.widget, forms.FileInput):
                field.widget.attrs.update({'class': 'form-control'})
            else:
                field.widget.attrs.update({'class': 'form-control'})

    def clean_agreed_to_terms(self):
        agreed = self.cleaned_data.get('agreed_to_terms')
        if not agreed:
            raise forms.ValidationError("You must agree to the terms and privacy policy.")
        return agreed
    
class ServicePartnerInterestForm(forms.ModelForm):
    class Meta:
        model = ServicePartnerInterest
        fields = ['message']
        widgets = {
            'message': forms.Textarea(attrs={
                'rows': 4,
                'class': 'form-control',
                'placeholder': 'Write a short note about the type of assistance you need...'
            }),
        }