from django import forms
from .models import Job, Profile, TradePosition, RecruiterProfile, IndustryMaster
from ckeditor.widgets import CKEditorWidget
from .validators import validate_age_18, validate_mobile_number, validate_experience, validate_videsh_email
import re


# --- Custom Field to handle 'Other' string for Trades ---
class TradeChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.title

    def to_python(self, value):
        if value == 'other':
            return 'other'
        return super().to_python(value)

    def validate(self, value):
        if value == 'other':
            return
        return super().validate(value)

# --- ✅ NEW: Custom Field to handle 'Other' string for Industry ---
class IndustryChoiceField(forms.ModelChoiceField):
    def to_python(self, value):
        if value == 'other':
            return 'other'
        return super().to_python(value)

    def validate(self, value):
        if value == 'other':
            return
        return super().validate(value)


class JobPostForm(forms.ModelForm):
    # ✅ Dropdowns ko custom fields mein badla
    industry_master = IndustryChoiceField(
        queryset=IndustryMaster.objects.all(),
        required=True,
        widget=forms.Select(attrs={'class': 'form-select'}),
        label="Industry"
    )
    position = TradeChoiceField(
        queryset=TradePosition.objects.all(),
        required=False,
        widget=forms.Select(attrs={'class': 'form-select'}),
        label="Position/Trade"
    )
    
    class Meta:
        model = Job
        fields = ['title', 'image', 'industry_master', 'other_industry_name', 'position', 'other_position_name', 'vacancies', 'salary', 'country', 'age_limit', 'PCC',
                  'contract_period', 'job_type', 'experience', 'working_hours', 'overtime', 'day_off', 'accommodation', 'food', 'transportation',
                  'language', 'description']
        
        widgets = {
            'description': CKEditorWidget(),
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Job Title'}),
            'country': forms.Select(attrs={'class': 'form-select'}),
            'other_industry_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Specify industry name'}),
            'other_position_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Specify trade/post name'}),
            'job_type': forms.Select(attrs={'class': 'form-select'}),
            'PCC': forms.Select(attrs={'class': 'form-select'}),
            'experience': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Experience in years'}),
            'age_limit': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'e.g., 18-45'}),
            'vacancies': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Number of Vacancies'}),
            'salary': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Enter Salary in INR'}),
            'contract_period': forms.Select(attrs={'class': 'form-select'}),
            'working_hours': forms.Select(attrs={'class': 'form-select'}),
            'overtime': forms.Select(attrs={'class': 'form-select'}),
            'day_off': forms.Select(attrs={'class': 'form-select'}),
            'accommodation': forms.Select(attrs={'class': 'form-select'}),
            'food': forms.Select(attrs={'class': 'form-select'}),
            'transportation': forms.Select(attrs={'class': 'form-select'}),
            'language': forms.TextInput(attrs={'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['industry_master'].choices = list(self.fields['industry_master'].choices) + [('other', 'Other (Mera industry list mein nahi hai)')]

        if 'industry_master' in self.data:
            try:
                industry_id = int(self.data.get('industry_master'))
                self.fields['position'].queryset = TradePosition.objects.filter(industry_id=industry_id)
            except (ValueError, TypeError): pass
        
        # ✅ AUTO-SYNC LOGIC: Check if 'Other' input is now a verified Master Trade
        if self.instance and self.instance.pk:
            ind_obj = self.instance.industry_master
            pos_obj = self.instance.position
            oth_ind = self.instance.other_industry_name
            oth_pos = self.instance.other_position_name

            # 1. Check Industry Match
            if not ind_obj and oth_ind:
                clean_oth_ind = re.sub(r'\s+', '', oth_ind).lower()
                matched_ind = IndustryMaster.objects.filter(name__iexact=oth_ind).first()
                if matched_ind:
                    self.initial['industry_master'] = matched_ind.id
                    self.initial['other_industry_name'] = ""
                    ind_obj = matched_ind # Update local ref for position check
                else:
                    self.initial['industry_master'] = 'other'

            # 2. Check Position Match (Only if industry is known)
            if not pos_obj and oth_pos and ind_obj:
                clean_oth_pos = re.sub(r'\s+', '', oth_pos).lower()
                # verified trades mein dhoondo
                matched_pos = TradePosition.objects.filter(industry=ind_obj, title__iexact=oth_pos, is_verified=True).first()
                if matched_pos:
                    self.initial['position'] = matched_pos.id
                    self.initial['other_position_name'] = ""
                else:
                    self.initial['position'] = 'other'

    # ✅ Step 1: Field Level Cleaning (None Bypass)
    def clean_industry_master(self):
        val = self.cleaned_data.get('industry_master')
        raw_val = self.data.get('industry_master')
        return None if raw_val == 'other' else val

    def clean_position(self):
        val = self.cleaned_data.get('position')
        raw_val = self.data.get('position')
        return None if raw_val == 'other' else val

    # ✅ Step 2: Global Clean (The Brain)
    def clean(self):
        cleaned_data = super().clean()
        raw_ind = self.data.get('industry_master')
        raw_pos = self.data.get('position')
        other_ind_text = cleaned_data.get('other_industry_name')
        other_pos_text = cleaned_data.get('other_position_name')
        
        # --- A. Industry Master Logic ---
        industry_obj = cleaned_data.get('industry_master')

        if raw_ind == 'other':
            cleaned_data['other_industry_name'] = (other_ind_text or "").strip()
            if not other_ind_text:
                self.add_error('other_industry_name', "Bhai, industry ka naam likhna zaroori hai!")
            else:
                user_clean = re.sub(r'\s+', '', other_ind_text).lower()
                exists_ind = False
                for ind in IndustryMaster.objects.all():
                    if user_clean == re.sub(r'\s+', '', ind.name).lower():
                        self.add_error('other_industry_name', f"Bhai, '{other_ind_text}' toh dropdown mein pehle se hai. Wahan se select karein.")
                        exists_ind = True; break
                
                if not exists_ind:
                    industry_obj, _ = IndustryMaster.objects.get_or_create(name=other_ind_text.strip())
        else:
            cleaned_data['other_industry_name'] = ""

        # --- B. Position Master Logic ---
        if raw_pos == 'other':
            if not other_pos_text:
                self.add_error('other_position_name', "Specify the trade name here.")
            elif industry_obj:
                user_clean = re.sub(r'\s+', '', other_pos_text).lower()
                exists_pos = False
                for trade in TradePosition.objects.filter(industry=industry_obj):
                    if user_clean == re.sub(r'\s+', '', trade.title).lower():
                        self.add_error('other_position_name', f"Bhai, '{other_pos_text}' toh is industry ki list mein pehle se hai!")
                        exists_pos = True; break
                
                if not exists_pos:
                    TradePosition.objects.get_or_create(
                        industry=industry_obj,
                        title=other_pos_text.strip(),
                        defaults={'is_verified': False}
                    )
        else:
            cleaned_data['other_position_name'] = ""
            
        return cleaned_data


class RecruiterBrandingForm(forms.ModelForm):
    class Meta:
        model = RecruiterProfile
        fields = ['company_name', 'company_logo', 'website', 'company_description']
        widgets = {
            'company_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ex: Videsh Chalo Services'}),
            'website': forms.URLInput(attrs={'class': 'form-control', 'placeholder': 'https://www.videshchalo.com'}),
            'company_description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': 'Apni company ke baare mein batayein...'}),
            'company_logo': forms.ClearableFileInput(attrs={'class': 'form-control'}),
        }


class CandidateProfileForm(forms.ModelForm):
    preferred_industry = IndustryChoiceField(
        queryset=IndustryMaster.objects.all(),
        required=True,
        widget=forms.Select(attrs={'class': 'form-select'}),
        label="Preferred Industry"
    )
    preferred_position = TradeChoiceField(
        queryset=TradePosition.objects.all(),
        required=False,
        widget=forms.Select(attrs={'class': 'form-select'}),
        label="Preferred Position"
    )
    
    full_name = forms.CharField(
        max_length=100, 
        required=True, 
        label="Full Name",
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Your Full Name'})
    )

    email = forms.EmailField(
        required=True,
        validators=[validate_videsh_email],
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'email@example.com'})
    )

    class Meta:
        model = Profile
        fields = [
            'preferred_industry', 'other_preferred_industry', 'preferred_position', 'other_preferred_position', 'gender', 'dob', 'whatsapp_number', 'skills', 
            'qualification', 'experience_years', 'city', 'state', 'resume'
        ]
        
        widgets = {
            'dob': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'other_preferred_industry': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Apni industry yahan likhein'}),
            'other_preferred_position': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Apna trade yahan likhein'}),
            'gender': forms.Select(attrs={'class': 'form-select'}),
            'state': forms.Select(attrs={'class': 'form-select'}),
            'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter City Name'}),
            # ✅ WhatsApp widget mein 'required' attribute add kar diya
            'whatsapp_number': forms.TextInput(attrs={
                'class': 'form-control', 
                'placeholder': 'WhatsApp No. (Example: +91...)',
                'required': 'required' 
            }),
            'skills': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Mason, Helper, Plumber, etc.'}),
            'qualification': forms.TextInput(attrs={'class': 'form-control'}),
            'experience_years': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Years of experience'}),
            'resume': forms.ClearableFileInput(attrs={'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super(CandidateProfileForm, self).__init__(*args, **kwargs)
        self.order_fields(['full_name', 'email', 'gender', 'dob', 'whatsapp_number'])
        if 'whatsapp_number' in self.fields:
            self.fields['whatsapp_number'].required = True
            # Optional: UI mein bhi 'required' attribute add kar dein
            self.fields['whatsapp_number'].widget.attrs.update({'required': 'required'})
        self.fields['preferred_industry'].choices = list(self.fields['preferred_industry'].choices) + [('other', 'Other (Mera industry list mein nahi hai)')]

        if 'preferred_industry' in self.data:
            try:
                industry_id = int(self.data.get('preferred_industry'))
                self.fields['preferred_position'].queryset = TradePosition.objects.filter(industry_id=industry_id)
            except (ValueError, TypeError): pass
        
        # ✅ AUTO-SYNC LOGIC: For Candidate Profile
        if self.instance and self.instance.pk:
            ind_obj = self.instance.preferred_industry
            pos_obj = self.instance.preferred_position
            oth_ind = self.instance.other_preferred_industry
            oth_pos = self.instance.other_preferred_position

            # 1. Industry Discovery
            if not ind_obj and oth_ind:
                matched_ind = IndustryMaster.objects.filter(name__iexact=oth_ind.strip()).first()
                if matched_ind:
                    self.initial['preferred_industry'] = matched_ind.id
                    self.initial['other_preferred_industry'] = ""
                    ind_obj = matched_ind
                else:
                    self.initial['preferred_industry'] = 'other'

            # 2. Position Discovery (Truck Driver matching)
            if not pos_obj and oth_pos and ind_obj:
                # Find verified matching trade in this industry
                matched_pos = TradePosition.objects.filter(industry=ind_obj, title__iexact=oth_pos.strip(), is_verified=True).first()
                if matched_pos:
                    self.initial['preferred_position'] = matched_pos.id
                    self.initial['other_preferred_position'] = ""
                else:
                    self.initial['preferred_position'] = 'other'

    def clean_preferred_industry(self):
        # Asli object uthao jo Django ne ID se dhoonda hai
        val = self.cleaned_data.get('preferred_industry')
        raw_val = self.data.get('preferred_industry')
        if raw_val == 'other': 
            return None
        return val # Standard choice return karein

    def clean_preferred_position(self):
        val = self.cleaned_data.get('preferred_position')
        raw_val = self.data.get('preferred_position')
        if raw_val == 'other': 
            return None
        return val

    def clean(self):
        cleaned_data = super().clean()
        
        # 🔍 Check raw inputs
        raw_ind = self.data.get('preferred_industry')
        raw_pos = self.data.get('preferred_position')
        
        other_ind_text = cleaned_data.get('other_preferred_industry')
        other_pos_text = cleaned_data.get('other_preferred_position')

        # --- 1. Industry Cleanup & Auto-Master Logic ---
        industry_obj = cleaned_data.get('preferred_industry')

        if raw_ind == 'other':
            cleaned_data['other_preferred_industry'] = (other_ind_text or "").strip()
            if not other_ind_text:
                self.add_error('other_preferred_industry', "Bhai, apni industry yahan likhein.")
            else:
                # ✅ NAYA: Agar Industry nayi hai, toh usey Master List mein dalo
                industry_obj, _ = IndustryMaster.objects.get_or_create(
                    name=other_ind_text.strip()
                )
        else:
            cleaned_data['other_preferred_industry'] = ""

        # --- 2. Position Cleanup & Auto-Master Logic ---
        if raw_pos == 'other':
            if not other_pos_text:
                self.add_error('other_preferred_position', "Bhai, apna kaam (trade) yahan likhna zaroori hai!")
            elif industry_obj:
                # Pehle check karo ki duplicate toh nahi
                user_clean = re.sub(r'\s+', '', other_pos_text).lower()
                exists = False
                for trade in TradePosition.objects.filter(industry=industry_obj):
                    if user_clean == re.sub(r'\s+', '', trade.title).lower():
                        self.add_error('other_preferred_position', f"Bhai, '{other_pos_text}' toh list mein pehle se hai!")
                        exists = True
                        break
                
                # ✅ MASTER CREATION: Agar sab sahi hai, toh Master List mein dalo
                if not exists:
                    TradePosition.objects.get_or_create(
                        industry=industry_obj,
                        title=other_pos_text.strip(),
                        defaults={'is_verified': False}
                    )
        else:
            cleaned_data['other_preferred_position'] = ""
            
        return cleaned_data


class RecruiterProfileForm(forms.ModelForm):
    class Meta:
        model = RecruiterProfile
        fields = [
            'company_name', 'industry', 'licence_number', 
            'contact_person', 'whatsapp_number', 'city', 
            'website', 'company_logo', 'company_description'
        ]
        widgets = {
            'company_description': CKEditorWidget(),
            'company_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ex: Videsh Chalo Services'}),
            'industry': forms.Select(attrs={'class': 'form-select'}),
            'licence_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Business Licence Number'}),
            'contact_person': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Contact Person Name'}),
            'whatsapp_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter WhatsApp Number'}),
            'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter City Name'}),
            'website': forms.URLInput(attrs={'class': 'form-control', 'placeholder': 'https://www.yourcompany.com'}),
            'company_logo': forms.ClearableFileInput(attrs={'class': 'form-control'}),
        }