from django import forms

from taxonomy.helpers import industry_choices, selected_value, sub_industry_choices
from companies.models import Company, CompanyProduct

COUNTRIES = [
    'Zambia', 'Angola', 'Botswana', 'Democratic Republic of the Congo', 'Kenya', 'Malawi', 'Mozambique',
    'Namibia', 'Nigeria', 'Rwanda', 'South Africa', 'Tanzania', 'Uganda', 'Zimbabwe',
    'United Kingdom', 'United States', 'India', 'China', 'United Arab Emirates', 'Other',
]
BENEFIT_PRESETS = [
    'Medical Insurance', 'Pension', 'Training & Development', 'Transport Allowance', 'Housing Allowance',
    'Performance Bonus', 'Wellness Programme', 'Flexible Working',
]
YES_NO = [('yes', 'Yes'), ('no', 'No')]
CTL = {'class': 'form-control'}


class TagsWidget(forms.Textarea):
    """One item per line, edited as chips in the browser (a plain textarea without JavaScript)."""

    def __init__(self, placeholder='Type and press Enter', suggestions=None, attrs=None):
        super().__init__(attrs={'rows': 3, 'class': 'form-control cp-tags-source', **(attrs or {})})
        self.placeholder = placeholder
        self.suggestions = suggestions or []

    def get_context(self, name, value, attrs):
        attrs = {**(attrs or {}), 'data-placeholder': self.placeholder, 'data-suggestions': '|'.join(self.suggestions)}
        return super().get_context(name, value, attrs)


class SectionForm(forms.ModelForm):
    examples = {}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, text in self.examples.items():
            if name in self.fields:
                self.fields[name].example = text


class InfoForm(SectionForm):
    logo = forms.ImageField(
        required=False, label='Company logo', widget=forms.FileInput(attrs={'accept': 'image/*'}),
        help_text='Upload your official company logo. It helps professionals recognise your company across PezaJob. PNG or JPG recommended.')
    clear_cover_image = forms.BooleanField(required=False, label='Remove the current cover image')
    industry = forms.ChoiceField(
        label='Industry', choices=industry_choices(),
        widget=forms.Select(attrs={'class': 'form-control', 'data-industry-for': 'id_sub_industry'}),
        help_text="Select the industry that best describes your company's main area of business.")
    sub_industry = forms.ChoiceField(
        label='Sub-industry', required=False, choices=[('', 'Select sub-industry')],
        widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_sub_industry'}),
        help_text='Narrows down your industry, so professionals and recruiters can find you more precisely.')
    company_type = forms.ChoiceField(
        label='Company type', choices=[('', 'Select company type')] + list(Company.CompanyType.choices),
        help_text='Tell us what type of organisation you are.')
    company_size = forms.ChoiceField(
        label='Company size', required=False, choices=[('', 'Select company size')] + list(Company.Size.choices),
        help_text='Approximately how many people work in your organisation? Optional.')
    is_public = forms.BooleanField(required=False, label='Show my company profile publicly on PezaJob')

    examples = {'name': 'Peza Career Hub Limited'}
    field_order = ['logo', 'cover_image', 'clear_cover_image', 'name', 'industry', 'sub_industry', 'company_type',
                   'founded_year', 'company_size', 'is_public']

    class Meta:
        model = Company
        fields = ['cover_image', 'name', 'founded_year', 'is_public']
        # 'industry' and 'sub_industry' are declared above as ChoiceFields (from the taxonomy), not model fields here
        labels = {'name': 'Company name', 'founded_year': 'Year established', 'cover_image': 'Cover image'}
        help_texts = {
            'cover_image': 'Add an image that represents your company: your workplace, team, operations, projects, products or facilities. Optional.',
            'name': 'Enter your official company or organisation name. It appears on your company profile and job adverts.',
            'founded_year': 'When was your company or organisation established? Optional.',
        }
        widgets = {
            'cover_image': forms.FileInput(attrs={'accept': 'image/*'}),
            'name': forms.TextInput(attrs=CTL),
            'founded_year': forms.NumberInput(attrs={**CTL, 'min': 1800, 'max': 2100, 'placeholder': 'YYYY'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for n in ('industry', 'company_type', 'company_size'):
            self.fields[n].widget.attrs['class'] = 'form-control'
        current = (self.instance.industry or '').strip()
        if current and current not in dict(self.fields['industry'].choices):
            self.fields['industry'].choices = list(self.fields['industry'].choices) + [(current, current)]
        self.initial.setdefault('industry', current)
        self.initial.setdefault('company_type', self.instance.company_type)
        self.initial.setdefault('company_size', self.instance.company_size)
        selected_industry = selected_value(self, 'industry', current)
        self.fields['sub_industry'].choices = sub_industry_choices(selected_industry) if selected_industry else [('', 'Select sub-industry')]
        current_sub = (self.instance.sub_industry or '').strip()
        if current_sub and current_sub not in dict(self.fields['sub_industry'].choices):
            self.fields['sub_industry'].choices = list(self.fields['sub_industry'].choices) + [(current_sub, current_sub)]
        self.initial.setdefault('sub_industry', current_sub)
        self.fields['sub_industry'].widget.attrs['data-initial'] = current_sub
        self.fields['name'].required = True

    def clean_founded_year(self):
        year = self.cleaned_data.get('founded_year')
        if year and not (1800 <= year <= 2100):
            raise forms.ValidationError('Enter a four digit year, for example 2015.')
        return year

    def save(self, commit=True):
        company = super().save(commit=False)
        company.industry = self.cleaned_data['industry']
        company.sub_industry = self.cleaned_data.get('sub_industry') or ''
        company.industry_slug = ''
        company.company_type = self.cleaned_data['company_type']
        company.company_size = self.cleaned_data.get('company_size') or ''
        if self.cleaned_data.get('clear_cover_image') and company.cover_image:
            company.cover_image.delete(save=False)
            company.cover_image = None
        if commit:
            company.save()
            logo = self.cleaned_data.get('logo')
            if logo and company.owner_id:
                owner = company.owner
                owner.avatar = logo
                owner.save(update_fields=['avatar'])
        return company


class AboutForm(SectionForm):
    examples = {
        'short_description': 'A Zambian mining company providing mineral development, engineering and mining services.',
        'description': 'ABC Mining Limited is a Zambian mining company focused on responsible mineral development and the delivery of mining, engineering and operational services.',
    }

    class Meta:
        model = Company
        fields = ['short_description', 'description']
        labels = {'short_description': 'Short company description', 'description': 'About the company'}
        help_texts = {
            'short_description': 'A short description of about 150 to 300 characters. It can appear on company cards, in search results, on job adverts and in recommendations.',
            'description': 'A longer description: who you are, what you do, the products or services you provide, who you serve, where you operate and what makes you unique. Use simple headings and paragraphs to organise it.',
        }
        widgets = {
            'short_description': forms.Textarea(attrs={**CTL, 'rows': 3, 'maxlength': 300, 'data-counter': '150-300', 'placeholder': 'Write a short description...'}),
            'description': forms.Textarea(attrs={**CTL, 'rows': 10, 'data-rich': '1', 'placeholder': 'Tell us about your company...'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['short_description'].required = True
        self.fields['short_description'].max_length = 300

    def clean_short_description(self):
        text = ' '.join((self.cleaned_data.get('short_description') or '').split())
        if len(text) < 50:
            raise forms.ValidationError('Please write at least 50 characters so professionals understand what you do (150 to 300 is ideal).')
        if len(text) > 300:
            raise forms.ValidationError('Keep the short description to 300 characters or fewer.')
        return text


class SpecialisationForm(SectionForm):
    class Meta:
        model = Company
        fields = ['specializations']
        labels = {'specializations': 'Areas of specialisation'}
        help_texts = {'specializations': 'Select the areas your company specialises in. You can add more than one. It helps professionals discover relevant companies.'}
        widgets = {'specializations': TagsWidget(
            'Add a specialisation and press Enter',
            ['Recruitment', 'Human Resources', 'Training & Development', 'Consulting', 'Technology',
             'Engineering', 'Mining', 'Agriculture', 'Finance', 'Marketing'])}


class LocationForm(SectionForm):
    country = forms.ChoiceField(label='Country', choices=[('', 'Select country')] + [(c, c) for c in COUNTRIES],
                                help_text='The country your head office is in.')
    province = forms.CharField(
        label='Province / region', required=False,
        widget=forms.TextInput(attrs={**CTL, 'list': 'cp-provinces', 'placeholder': 'Select or type a province or region'}))

    examples = {'city': 'Lusaka', 'address': 'Plot 123, Cairo Road'}
    field_order = ['country', 'province', 'city', 'address', 'other_locations']

    class Meta:
        model = Company
        fields = ['province', 'city', 'address', 'other_locations']
        labels = {'city': 'City / town', 'address': 'Physical address', 'other_locations': 'Other locations'}
        help_texts = {
            'city': 'Where is your main office? This is the location shown on your company card and job adverts.',
            'address': 'Street address or landmark of your head office.',
            'other_locations': 'Does your company operate from other locations? Add other branches, offices or operating locations, for example Kitwe, Ndola, Solwezi.',
        }
        widgets = {
            'city': forms.TextInput(attrs=CTL),
            'address': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter address'}),
            'other_locations': TagsWidget('Add a location and press Enter'),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['country'].widget.attrs['class'] = 'form-control'
        self.fields['city'].required = True
        self.initial.setdefault('country', self.instance.country or 'Zambia')

    def save(self, commit=True):
        company = super().save(commit=False)
        company.country = self.cleaned_data['country']
        company.location = company.city
        if commit:
            company.save()
        return company


class ContactForm(SectionForm):
    examples = {'email': 'company@email.com', 'phone': '+260...', 'recruitment_email': 'careers@company.com'}

    class Meta:
        model = Company
        fields = ['email', 'phone', 'website', 'recruitment_email', 'recruitment_phone',
                  'linkedin_url', 'facebook_url', 'x_url', 'instagram_url', 'youtube_url']
        labels = {
            'email': 'Company email', 'phone': 'Company phone number', 'website': 'Company website',
            'recruitment_email': 'Recruitment email', 'recruitment_phone': 'Recruitment phone',
            'linkedin_url': 'LinkedIn', 'facebook_url': 'Facebook', 'x_url': 'X', 'instagram_url': 'Instagram',
            'youtube_url': 'YouTube',
        }
        help_texts = {
            'email': 'Your main company email address. PezaJob may use it for important company-related communication.',
            'phone': 'Your main company contact number.',
            'website': 'Your official website. Leave blank if you do not have one.',
            'recruitment_email': 'Where recruitment-related communication should be sent, for example careers@company.com or hr@company.com. Optional.',
            'recruitment_phone': 'A number that can be used for recruitment-related communication. Optional.',
            'linkedin_url': 'Add your official social media pages so professionals can learn more about you. Only add official company accounts.',
        }
        widgets = {
            'email': forms.EmailInput(attrs=CTL),
            'phone': forms.TextInput(attrs=CTL),
            'website': forms.URLInput(attrs={**CTL, 'placeholder': 'https://...'}),
            'recruitment_email': forms.EmailInput(attrs=CTL),
            'recruitment_phone': forms.TextInput(attrs=CTL),
            'linkedin_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://linkedin.com/company/...'}),
            'facebook_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://facebook.com/...'}),
            'x_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://x.com/...'}),
            'instagram_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://instagram.com/...'}),
            'youtube_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://youtube.com/...'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['email'].required = True


class CareersForm(SectionForm):
    examples = {
        'careers_overview': 'We recruit professionals across engineering, finance, human resources, ICT, administration, sales, operations and supply chain.',
        'why_work_with_us': 'We provide employees with opportunities to develop their skills, work on meaningful projects and grow their careers in a collaborative professional environment.',
    }
    PROGRAMMES = [
        ('offers_internships', 'Do you offer internships?'),
        ('offers_graduate_roles', 'Do you offer graduate opportunities?'),
        ('offers_trainee_programmes', 'Do you offer graduate trainee programmes?'),
        ('offers_apprenticeships', 'Do you offer apprenticeships?'),
        ('recruits_experienced', 'Do you recruit experienced professionals?'),
    ]

    class Meta:
        model = Company
        fields = ['careers_overview', 'why_work_with_us']
        labels = {'careers_overview': 'What career opportunities do you offer?',
                  'why_work_with_us': 'Why should professionals consider working for you?'}
        help_texts = {
            'careers_overview': 'Tell us about the types of roles and career areas you normally recruit for.',
            'why_work_with_us': 'Tell professionals about the opportunities, environment and experiences you offer: career growth, training, exposure to major projects, innovation, leadership, team environment, work-life balance.',
        }
        widgets = {
            'careers_overview': forms.Textarea(attrs={**CTL, 'rows': 4, 'placeholder': 'Tell professionals about career opportunities...'}),
            'why_work_with_us': forms.Textarea(attrs={**CTL, 'rows': 5, 'placeholder': 'Why work with us?'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, label in self.PROGRAMMES:
            self.fields[name] = forms.ChoiceField(label=label, choices=YES_NO, widget=forms.RadioSelect, required=False)
            self.initial[name] = 'yes' if getattr(self.instance, name) else 'no'
        self.programme_fields = [self[n] for n, _ in self.PROGRAMMES]

    def save(self, commit=True):
        company = super().save(commit=False)
        for name, _ in self.PROGRAMMES:
            setattr(company, name, self.cleaned_data.get(name) == 'yes')
        if commit:
            company.save()
        return company


class BrandForm(SectionForm):
    benefit_options = forms.MultipleChoiceField(
        required=False, label='Employee benefits', choices=[(b, b) for b in BENEFIT_PRESETS],
        widget=forms.CheckboxSelectMultiple,
        help_text='What benefits or employee support does your company provide? Only select benefits your company actually provides.')
    benefits_other = forms.CharField(
        required=False, label='Other benefits', widget=TagsWidget('Add another benefit and press Enter'),
        help_text='Anything else you offer that is not in the list above.')

    examples = {'culture': 'We promote teamwork, accountability, continuous learning and an inclusive working environment where employees are encouraged to contribute ideas and develop professionally.'}
    field_order = ['culture', 'values', 'benefit_options', 'benefits_other']

    class Meta:
        model = Company
        fields = ['culture', 'values']
        labels = {'culture': 'Company culture', 'values': 'Our values'}
        help_texts = {
            'culture': 'What is it like to work at your company? Describe your working environment, values, teamwork, leadership style or employee experience. Optional.',
            'values': 'What values guide your organisation? Add the values that represent your company.',
        }
        widgets = {
            'culture': forms.Textarea(attrs={**CTL, 'rows': 5, 'placeholder': 'Describe your company culture...'}),
            'values': TagsWidget('Add a value and press Enter',
                                 ['Integrity', 'Innovation', 'Teamwork', 'Excellence', 'Customer Focus', 'Safety', 'Accountability']),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        current = self.instance.benefit_list
        self.initial['benefit_options'] = [b for b in current if b in BENEFIT_PRESETS]
        self.initial['benefits_other'] = '\n'.join(b for b in current if b not in BENEFIT_PRESETS)

    def save(self, commit=True):
        company = super().save(commit=False)
        chosen = list(self.cleaned_data.get('benefit_options') or [])
        other = [b.strip() for b in (self.cleaned_data.get('benefits_other') or '').splitlines() if b.strip()]
        company.benefits = '\n'.join(chosen + [o for o in other if o not in chosen])
        if commit:
            company.save()
        return company


class VerificationForm(SectionForm):
    clear_registration_document = forms.BooleanField(required=False, label='Remove the uploaded document')

    examples = {'rep_position': 'HR Manager'}
    field_order = ['registered_name', 'registration_number', 'registration_country', 'registration_document',
                   'clear_registration_document', 'rep_name', 'rep_position', 'rep_email', 'rep_phone']

    class Meta:
        model = Company
        fields = ['registered_name', 'registration_number', 'registration_country', 'registration_document',
                  'rep_name', 'rep_position', 'rep_email', 'rep_phone']
        labels = {
            'registered_name': 'Registered company name', 'registration_number': 'Company registration number',
            'registration_country': 'Country of registration', 'registration_document': 'Registration certificate',
            'rep_name': 'Full name', 'rep_position': 'Position', 'rep_email': 'Work email', 'rep_phone': 'Phone number',
        }
        help_texts = {
            'registered_name': 'Provide your official company information to help PezaJob verify your organisation. It is not shown publicly.',
            'registration_document': 'Optional. A copy of your certificate of incorporation or registration. Kept private and used only for verification.',
            'rep_name': 'Who manages this company profile? Enter the details of the person responsible for your PezaJob account.',
        }
        widgets = {
            'registered_name': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter registered name'}),
            'registration_number': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter registration number'}),
            'registration_country': forms.TextInput(attrs={**CTL, 'list': 'cp-countries', 'placeholder': 'Select country'}),
            'registration_document': forms.FileInput(attrs={'accept': '.pdf,.jpg,.jpeg,.png'}),
            'rep_name': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter full name'}),
            'rep_position': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter position'}),
            'rep_email': forms.EmailInput(attrs={**CTL, 'placeholder': 'Enter work email'}),
            'rep_phone': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter phone number'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for n in ('rep_name', 'rep_position', 'rep_email'):
            self.fields[n].required = True

    def save(self, commit=True):
        company = super().save(commit=False)
        if self.cleaned_data.get('clear_registration_document') and company.registration_document:
            company.registration_document.delete(save=False)
            company.registration_document = None
        if commit:
            company.save()
        return company


class ProductForm(forms.ModelForm):
    class Meta:
        model = CompanyProduct
        fields = ['name', 'description', 'image']
        widgets = {
            'name': forms.TextInput(attrs={**CTL, 'placeholder': 'Enter name'}),
            'description': forms.Textarea(attrs={**CTL, 'rows': 3, 'placeholder': 'Describe the product or service...'}),
            'image': forms.FileInput(attrs={'accept': 'image/*'}),
        }


SECTION_FORMS = {
    'info': InfoForm,
    'about': AboutForm,
    'products': SpecialisationForm,
    'locations': LocationForm,
    'contact': ContactForm,
    'careers': CareersForm,
    'brand': BrandForm,
    'verification': VerificationForm,
}
PROVINCES = ['Central', 'Copperbelt', 'Eastern', 'Luapula', 'Lusaka', 'Muchinga',
             'Northern', 'North-Western', 'Southern', 'Western']
