from django import forms

from taxonomy.helpers import active_tree, industry_choices, selected_value, sub_industry_choices
from employers.company_forms import COUNTRIES, TagsWidget

from .models import (
    Achievement, Certification, Education, Membership, ProfessionalReference, Project, SeekerProfile,
    SpokenLanguage, VolunteerExperience, WorkExperience,
)

CTL = {'class': 'form-control'}
MONTHS = [('', 'Month')] + [(i, n) for i, n in enumerate(
    ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
     'November', 'December'], 1)]
EMPLOYMENT_TYPES = ['Full-Time', 'Part-Time', 'Contract', 'Temporary', 'Internship', 'Freelance', 'Consultancy']
WORK_ARRANGEMENTS = ['On-Site', 'Hybrid', 'Remote']
WORK_AUTH = ['I am eligible to work in Zambia', 'I am eligible to work in other countries',
             'I require a work permit', 'I require employer sponsorship', 'Other']
LANGUAGES = ['English', 'Bemba', 'Nyanja', 'Tonga', 'Lozi', 'Kaonde', 'Lunda', 'Luvale', 'French', 'Portuguese',
             'Swahili', 'Afrikaans', 'Arabic', 'Chinese', 'German', 'Spanish']


def _skill_suggestions():
    try:
        from ats.matching_engine import SKILL_DISPLAY
        return sorted(set(SKILL_DISPLAY.values()))
    except Exception:
        return []


def _year(label, **kw):
    return forms.IntegerField(required=False, label=label, min_value=1940, max_value=2100,
                              widget=forms.NumberInput(attrs={**CTL, 'placeholder': 'YYYY'}), **kw)


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 BasicsForm(SectionForm):
    photo = forms.ImageField(
        required=False, label='Profile photo', widget=forms.FileInput(attrs={'accept': 'image/*'}),
        help_text='Upload a professional photo to help employers put a face to your profile. Use a clear photo where your face is easily visible.')
    first_name = forms.CharField(label='First name', max_length=60, widget=forms.TextInput(attrs=CTL))
    last_name = forms.CharField(label='Last name', max_length=60, required=False, widget=forms.TextInput(attrs=CTL))
    city = forms.CharField(label='City / town', max_length=100, widget=forms.TextInput(attrs=CTL),
                           help_text='Where you are based. Employers use this to find people near them.')
    country = forms.ChoiceField(label='Country', choices=[('', 'Select country')] + [(c, c) for c in COUNTRIES])
    industry = forms.ChoiceField(label='Industry', required=False, choices=industry_choices(),
                                 widget=forms.Select(attrs={'class': 'form-control', 'data-industry-for': 'id_sub_industry'}),
                                 help_text='The industry you work in or want to work in.')
    professional_status = forms.ChoiceField(
        label='Current professional status', required=False,
        choices=[('', 'Select')] + list(SeekerProfile.ProfessionalStatus.choices))
    years_experience = forms.TypedChoiceField(
        label='Years of professional experience', coerce=int, empty_value=0,
        choices=[(i, 'Less than 1 year' if i == 0 else f'{i} year{"s" if i != 1 else ""}') for i in range(0, 40)] + [(40, '40+ years')],
        help_text='Total years of professional experience across all your roles.')
    clear_cover_image = forms.BooleanField(required=False, label='Remove the current cover photo')

    examples = {'headline': 'Sales Manager | Business Development | FMCG & Manufacturing'}
    field_order = ['photo', 'show_photo', 'cover_image', 'clear_cover_image', 'first_name', 'last_name', 'headline',
                   'current_job_title', 'current_employer', 'industry', 'sub_industry', 'city', 'country',
                   'years_experience', 'professional_status']

    class Meta:
        model = SeekerProfile
        fields = ['show_photo', 'cover_image', 'headline', 'current_job_title', 'current_employer', 'sub_industry']
        labels = {'show_photo': 'Show my photo to employers and recruiters', 'headline': 'Professional headline',
                  'current_job_title': 'Current job title', 'current_employer': 'Current employer',
                  'sub_industry': 'Sub-industry', 'cover_image': 'Cover photo'}
        widgets = {}  # sub_industry widget is set in __init__ once the chosen industry is known
        help_texts = {
            'headline': 'Your headline helps employers quickly understand what you do.',
            'current_employer': 'Search or enter the company name. Leave blank if you are not currently employed.',
            'cover_image': 'Optional banner shown at the top of your public profile. 1200 x 400 px or wider works best.',
        }
        widgets = {
            'cover_image': forms.FileInput(attrs={'accept': 'image/*'}),
            'headline': forms.TextInput(attrs=CTL),
            'current_job_title': forms.TextInput(attrs=CTL),
            'current_employer': forms.TextInput(attrs={**CTL, 'placeholder': 'Search or enter company name', 'list': 'sp-companies'}),
            'sub_industry': forms.Select(attrs={**CTL, 'id': 'id_sub_industry'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        p = self.instance
        self.initial.update({
            'first_name': p.first_name, 'last_name': p.last_name, 'city': p.location,
            'country': p.country or 'Zambia', 'industry': p.industry, 'professional_status': p.professional_status,
            'years_experience': p.years_experience,
        })
        current = (p.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)]
        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 = (p.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.fields['sub_industry'].widget.attrs['data-initial'] = current_sub
        self.fields['headline'].required = True

    def save(self, commit=True):
        p = super().save(commit=False)
        cd = self.cleaned_data
        p.full_name = ' '.join(x for x in (cd['first_name'].strip(), (cd.get('last_name') or '').strip()) if x)
        p.location = cd['city'].strip()
        p.country = cd['country']
        p.industry = cd.get('industry') or ''
        p.professional_status = cd.get('professional_status') or ''
        p.years_experience = cd['years_experience']
        if cd.get('clear_cover_image') and p.cover_image:
            p.cover_image.delete(save=False)
            p.cover_image = None
        if commit:
            p.save()
            photo = cd.get('photo')
            if photo and p.user_id:
                p.user.avatar = photo
                p.user.save(update_fields=['avatar'])
        return p


class AboutForm(SectionForm):
    examples = {
        'bio': 'Experienced Sales Manager with 8 years of experience in FMCG, manufacturing and distribution. Skilled in sales strategy, team leadership, key account management and business development, with a strong track record of growing revenue and developing customer relationships.',
    }

    class Meta:
        model = SeekerProfile
        fields = ['bio', 'products_experience']
        labels = {'bio': 'Professional summary', 'products_experience': 'Products and services you have worked with'}
        help_texts = {
            'bio': 'Tell employers about yourself, your professional background, strengths and the value you bring. Keep it professional and focus on your experience, expertise and career strengths.',
            'products_experience': 'Add products, services or solutions you have experience selling, managing, producing, supporting or working with. Be specific where possible, it can help match you with specialised opportunities.',
        }
        widgets = {
            'bio': forms.Textarea(attrs={**CTL, 'rows': 8, 'placeholder': 'Tell employers about yourself...'}),
            'products_experience': TagsWidget('Add a product or service and press Enter', [
                'Plastic packaging', 'Beverages', 'Agricultural inputs', 'Seeds', 'Fertiliser', 'Automotive parts',
                'Building materials', 'Insurance', 'Financial services', 'Telecommunications', 'Medical products']),
        }

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


class SkillsForm(SectionForm):
    class Meta:
        model = SeekerProfile
        fields = ['skills']
        labels = {'skills': 'Your professional skills'}
        help_texts = {'skills': 'Add skills that represent what you can do professionally. Pick from the suggestions or type your own and press Enter. Focus on skills relevant to the work you want.'}
        widgets = {'skills': TagsWidget('Type to search or add a skill', _skill_suggestions(), attrs={'data-show': '14'})}


class PreferencesForm(SectionForm):
    employment_options = forms.MultipleChoiceField(
        required=False, label='Employment types', choices=[(x, x) for x in EMPLOYMENT_TYPES],
        widget=forms.CheckboxSelectMultiple, help_text='What type of work are you interested in?')
    arrangement_options = forms.MultipleChoiceField(
        required=False, label='Preferred work arrangement', choices=[(x, x) for x in WORK_ARRANGEMENTS],
        widget=forms.CheckboxSelectMultiple)
    authorisation_options = forms.MultipleChoiceField(
        required=False, label='Work authorisation', choices=[(x, x) for x in WORK_AUTH],
        widget=forms.CheckboxSelectMultiple)
    available_from = forms.DateField(required=False, label='Available from', widget=forms.DateInput(attrs={**CTL, 'type': 'date'}, format='%Y-%m-%d'))

    field_order = ['target_titles', 'preferred_industries', 'preferred_categories', 'preferred_locations',
                   'employment_options', 'arrangement_options', 'willing_to_relocate', 'relocation_locations',
                   'availability', 'availability_timeline', 'available_from',
                   'salary_min', 'salary_max', 'salary_currency', 'salary_negotiable', 'salary_private',
                   'authorised_countries', 'authorisation_options']

    class Meta:
        model = SeekerProfile
        fields = ['target_titles', 'preferred_industries', 'preferred_categories', 'preferred_locations',
                  'willing_to_relocate', 'relocation_locations', 'availability', 'availability_timeline',
                  'salary_min', 'salary_max', 'salary_currency', 'salary_negotiable', 'salary_private',
                  'authorised_countries']
        labels = {
            'target_titles': 'Target job titles', 'preferred_industries': 'Preferred industries',
            'preferred_categories': 'Preferred job categories', 'preferred_locations': 'Preferred locations',
            'willing_to_relocate': 'I am willing to relocate', 'relocation_locations': 'Locations or countries I am willing to relocate to',
            'availability': 'Job search status', 'availability_timeline': 'When are you available for a new opportunity?',
            'salary_min': 'Minimum expected salary (per month)', 'salary_max': 'Preferred salary (per month)',
            'salary_currency': 'Currency', 'salary_negotiable': 'Salary is negotiable',
            'salary_private': 'I prefer not to disclose my salary expectations',
            'authorised_countries': 'Countries where I am authorised to work',
        }
        help_texts = {
            'target_titles': 'Tell us what positions you are interested in. You can add more than one.',
            'preferred_industries': 'Industries you would like to work in.',
            'preferred_categories': 'Job categories you would like to work in.',
            'preferred_locations': 'Where you would like to work.',
            'availability': 'Employers can filter by this in Find Talent.',
            'salary_min': 'Providing salary expectations can help us identify opportunities that are more suitable for you.',
        }
        widgets = {
            'target_titles': TagsWidget('Add a job title and press Enter', ['Sales Manager', 'Business Development Manager', 'Commercial Manager']),
            'preferred_industries': TagsWidget('Add an industry and press Enter', list(active_tree().keys())),
            'preferred_categories': TagsWidget('Add a category and press Enter'),
            'preferred_locations': TagsWidget('Add a location and press Enter', ['Lusaka', 'Kitwe', 'Ndola', 'Livingstone', 'Solwezi']),
            'relocation_locations': forms.TextInput(attrs=CTL),
            'availability': forms.Select(attrs=CTL),
            'availability_timeline': forms.Select(attrs=CTL),
            'salary_min': forms.NumberInput(attrs={**CTL, 'min': 0}),
            'salary_max': forms.NumberInput(attrs={**CTL, 'min': 0}),
            'salary_currency': forms.Select(attrs=CTL, choices=[('ZMW', 'ZMW'), ('USD', 'USD'), ('ZAR', 'ZAR'), ('EUR', 'EUR'), ('GBP', 'GBP')]),
            'authorised_countries': TagsWidget('Add a country and press Enter', ['Zambia']),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        p = self.instance
        self.fields['availability_timeline'].choices = [('', 'Select')] + list(SeekerProfile.Timeline.choices)
        self.initial['employment_options'] = p.employment_type_list
        self.initial['arrangement_options'] = p.work_arrangement_list
        others = [a for a in p.work_authorisation_list if a not in WORK_AUTH]
        self.initial['authorisation_options'] = [a for a in p.work_authorisation_list if a in WORK_AUTH] + others

    def clean(self):
        data = super().clean()
        low, high = data.get('salary_min'), data.get('salary_max')
        if low and high and high < low:
            self.add_error('salary_max', 'Preferred salary should not be lower than the minimum.')
        if data.get('availability_timeline') == 'date' and not data.get('available_from'):
            self.add_error('available_from', 'Choose the date you are available from.')
        return data

    def save(self, commit=True):
        p = super().save(commit=False)
        cd = self.cleaned_data
        p.employment_types = '\n'.join(cd.get('employment_options') or [])
        p.work_arrangements = '\n'.join(cd.get('arrangement_options') or [])
        p.work_authorisation = '\n'.join(cd.get('authorisation_options') or [])
        p.available_from = cd.get('available_from') if cd.get('availability_timeline') == 'date' else None
        if not p.willing_to_relocate:
            p.relocation_locations = ''
        if commit:
            p.save()
        return p


class CvLinksForm(SectionForm):
    clear_cv = forms.BooleanField(required=False, label='Remove my CV')

    field_order = ['cv_file', 'clear_cv', 'allow_cv_access', 'linkedin_url', 'website_url', 'portfolio_url', 'github_url', 'other_link_url']

    class Meta:
        model = SeekerProfile
        fields = ['cv_file', 'allow_cv_access', 'linkedin_url', 'website_url', 'portfolio_url', 'github_url', 'other_link_url']
        labels = {
            'cv_file': 'Your CV', 'allow_cv_access': 'Allow employers and recruiters to access my CV when appropriate',
            'linkedin_url': 'LinkedIn', 'website_url': 'Personal website', 'portfolio_url': 'Portfolio',
            'github_url': 'GitHub', 'other_link_url': 'Other professional link',
        }
        help_texts = {
            'cv_file': 'Upload your most recent CV to make your profile more useful to employers and recruiters. Accepted formats: PDF, DOC, DOCX (photos and scans of a CV are read too). Keep it updated with your latest experience, education and skills.',
            'linkedin_url': 'Add links that help employers learn more about your professional work.',
        }
        widgets = {
            'cv_file': forms.FileInput(attrs={'accept': '.pdf,.doc,.docx,.txt,.rtf,.odt,.jpg,.jpeg,.png'}),
            'linkedin_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://linkedin.com/in/...'}),
            'website_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://...'}),
            'portfolio_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://...'}),
            'github_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://github.com/...'}),
            'other_link_url': forms.URLInput(attrs={**CTL, 'placeholder': 'https://...'}),
        }

    def save(self, commit=True):
        p = super().save(commit=False)
        if self.cleaned_data.get('clear_cv') and p.cv_file and 'cv_file' not in self.files:
            p.cv_file.delete(save=False)
            p.cv_file = None
        if commit:
            p.save()
        return p


class PrivacyForm(SectionForm):
    phone = forms.CharField(label='Phone number', required=False, max_length=30, widget=forms.TextInput(attrs=CTL))
    visibility = forms.ChoiceField(
        label='Who can see your professional profile?', choices=SeekerProfile.Visibility.choices, widget=forms.RadioSelect)
    contact_visibility = forms.ChoiceField(
        label='Who can see your contact information?', widget=forms.RadioSelect,
        choices=[('both', 'Employers, recruiters and the PezaJob recruitment team'),
                 ('employers', 'Employers and recruiters only'),
                 ('team', 'The PezaJob recruitment team only'),
                 ('nobody', 'Nobody, keep my contact details private')])

    field_order = ['phone', 'contact_visibility', 'visibility', 'consent_contact', 'consent_present', 'consent_matching', 'confirm_accuracy', 'is_online']

    class Meta:
        model = SeekerProfile
        fields = ['consent_contact', 'consent_present', 'consent_matching', 'confirm_accuracy', 'is_online']
        labels = {
            'consent_contact': 'I am open to being contacted by PezaJob about relevant job opportunities.',
            'consent_present': 'I allow PezaJob to present my profile to relevant employers when I am being considered for an opportunity.',
            'consent_matching': 'I understand that I may be contacted about opportunities that match my professional profile and preferences.',
            'confirm_accuracy': 'I confirm that the information provided in my profile is accurate and up to date.',
            'is_online': 'Show me as online',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        p = self.instance
        self.initial['phone'] = p.user.phone if p.user_id else ''
        self.initial['visibility'] = p.visibility
        self.initial['contact_visibility'] = (
            'both' if p.contact_employers and p.contact_team else 'employers' if p.contact_employers
            else 'team' if p.contact_team else 'nobody')

    def save(self, commit=True):
        p = super().save(commit=False)
        cd = self.cleaned_data
        p.visibility = cd['visibility']
        p.is_public = cd['visibility'] != SeekerProfile.Visibility.PRIVATE
        p.contact_employers = cd['contact_visibility'] in ('both', 'employers')
        p.contact_team = cd['contact_visibility'] in ('both', 'team')
        if commit:
            p.save()
            if p.user_id:
                p.user.phone = cd.get('phone', '')
                p.user.save(update_fields=['phone'])
        return p


# ---- Repeatable items -----------------------------------------------------------------

def _item_form(model, fields, widgets=None, labels=None, extra=None, required=()):
    attrs = {'model': model, 'fields': fields, 'widgets': widgets or {}, 'labels': labels or {}}
    meta = type('Meta', (), attrs)
    body = {'Meta': meta}
    body.update(extra or {})

    def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        for name in required:
            self.fields[name].required = True

    body['__init__'] = __init__
    return type(model.__name__ + 'Form', (forms.ModelForm,), body)


_T = lambda ph='': forms.TextInput(attrs={**CTL, 'placeholder': ph} if ph else CTL)
_A = lambda rows=3, ph='': forms.Textarea(attrs={**CTL, 'rows': rows, 'placeholder': ph})
_U = lambda ph='https://...': forms.URLInput(attrs={**CTL, 'placeholder': ph})


class ExperienceForm(forms.ModelForm):
    start_month = forms.TypedChoiceField(required=False, choices=MONTHS, coerce=int, empty_value=None, label='Start month', widget=forms.Select(attrs=CTL))
    end_month = forms.TypedChoiceField(required=False, choices=MONTHS, coerce=int, empty_value=None, label='End month', widget=forms.Select(attrs=CTL))

    class Meta:
        model = WorkExperience
        fields = ['company', 'title', 'job_category', 'industry', 'sub_industry', 'employment_type', 'location',
                  'start_month', 'start_year', 'is_current', 'end_month', 'end_year', 'responsibilities', 'achievements']
        labels = {'company': 'Company / organisation', 'title': 'Job title', 'job_category': 'Job category', 'industry': 'Industry',
                  'sub_industry': 'Sub-industry', 'employment_type': 'Employment type', 'location': 'Location',
                  'start_year': 'Start year', 'end_year': 'End year', 'is_current': 'I currently work here',
                  'responsibilities': 'Responsibilities', 'achievements': 'Achievements'}
        widgets = {
            'company': _T('Search for a company or enter company name'), 'title': _T(), 'job_category': _T('For example: Sales & Marketing'),
            'industry': forms.Select(attrs=CTL), 'sub_industry': _T(), 'employment_type': forms.Select(attrs=CTL), 'location': _T(),
            'start_year': forms.NumberInput(attrs={**CTL, 'placeholder': 'YYYY', 'min': 1940, 'max': 2100}),
            'end_year': forms.NumberInput(attrs={**CTL, 'placeholder': 'YYYY', 'min': 1940, 'max': 2100}),
            'responsibilities': _A(4, 'What were you responsible for in this role?'),
            'achievements': _A(3, 'What did you accomplish in this role?'),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['industry'] = forms.ChoiceField(required=False, label='Industry', choices=industry_choices(),
                                                    widget=forms.Select(attrs={**CTL, 'data-industry-for': self.add_prefix('sub_industry')}))
        fallback_industry = self.initial.get('industry') or getattr(self.instance, 'industry', '') or ''
        selected_industry = selected_value(self, 'industry', fallback_industry)
        self.fields['sub_industry'] = forms.ChoiceField(
            required=False, label='Sub-industry',
            choices=sub_industry_choices(selected_industry),
            widget=forms.Select(attrs={**CTL, 'id': self.add_prefix('sub_industry')}))
        current_sub = getattr(self.instance, 'sub_industry', '') or ''
        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.fields['sub_industry'].widget.attrs['data-initial'] = current_sub
        self.fields['employment_type'].choices = [('', 'Select')] + list(WorkExperience.EmploymentType.choices)
        self.fields['start_year'].required = True

    def clean(self):
        d = super().clean()
        if not d.get('is_current'):
            sy, ey = d.get('start_year'), d.get('end_year')
            if not ey:
                self.add_error('end_year', 'Add the year you left, or tick "I currently work here".')
            elif sy and ey < sy:
                self.add_error('end_year', 'The end year cannot be before the start year.')
        else:
            d['end_month'], d['end_year'] = None, None
        return d


class EducationForm(forms.ModelForm):
    class Meta:
        model = Education
        fields = ['institution', 'qualification', 'field_of_study', 'level', 'start_year', 'end_year']
        labels = {'institution': 'Institution', 'qualification': 'Qualification', 'field_of_study': 'Field of study',
                  'level': 'Education level', 'start_year': 'Start year', 'end_year': 'End year'}
        widgets = {'institution': _T(), 'qualification': _T(), 'field_of_study': _T(), 'level': forms.Select(attrs=CTL),
                   'start_year': forms.NumberInput(attrs={**CTL, 'placeholder': 'YYYY'}),
                   'end_year': forms.NumberInput(attrs={**CTL, 'placeholder': 'YYYY'})}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['level'].choices = [('', 'Select')] + list(Education.Level.choices)

    def clean(self):
        d = super().clean()
        if d.get('start_year') and d.get('end_year') and d['end_year'] < d['start_year']:
            self.add_error('end_year', 'The end year cannot be before the start year.')
        return d


class CertificationForm(forms.ModelForm):
    class Meta:
        model = Certification
        fields = ['name', 'issuer', 'date_obtained', 'expiry_date', 'credential_number']
        labels = {'name': 'Certification name', 'issuer': 'Issuing organisation', 'date_obtained': 'Date obtained',
                  'expiry_date': 'Expiry date (if applicable)', 'credential_number': 'Credential / certificate number'}
        widgets = {'name': _T(), 'issuer': _T(),
                   'date_obtained': forms.DateInput(attrs={**CTL, 'type': 'date'}, format='%Y-%m-%d'),
                   'expiry_date': forms.DateInput(attrs={**CTL, 'type': 'date'}, format='%Y-%m-%d'),
                   'credential_number': _T()}

    def clean(self):
        d = super().clean()
        if d.get('date_obtained') and d.get('expiry_date') and d['expiry_date'] < d['date_obtained']:
            self.add_error('expiry_date', 'The expiry date cannot be before the date obtained.')
        return d


class LanguageForm(forms.ModelForm):
    language = forms.CharField(label='Language', max_length=60, widget=forms.TextInput(attrs={**CTL, 'list': 'sp-languages', 'placeholder': 'Select or type a language'}))

    class Meta:
        model = SpokenLanguage
        fields = ['language', 'proficiency']
        labels = {'proficiency': 'Proficiency'}
        widgets = {'proficiency': forms.Select(attrs=CTL)}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['proficiency'].choices = [('', 'Select')] + list(SpokenLanguage.Proficiency.choices)


ProjectForm = _item_form(Project, ['name', 'role', 'organisation', 'date', 'description', 'link'],
                         widgets={'name': _T(), 'role': _T(), 'organisation': _T(), 'date': _T('For example: 2024'),
                                  'description': _A(4), 'link': _U()},
                         labels={'name': 'Project name', 'role': 'Your role', 'organisation': 'Organisation / client', 'date': 'Date',
                                 'description': 'Project description', 'link': 'Project link'})
MembershipForm = _item_form(Membership, ['organisation', 'membership_type', 'membership_number'],
                            widgets={'organisation': _T(), 'membership_type': _T(), 'membership_number': _T()},
                            labels={'organisation': 'Organisation', 'membership_type': 'Membership type', 'membership_number': 'Membership number'})
AchievementForm = _item_form(Achievement, ['title', 'organisation', 'year', 'description'],
                             widgets={'title': _T(), 'organisation': _T(), 'year': forms.NumberInput(attrs={**CTL, 'placeholder': 'YYYY'}),
                                      'description': _A(3)},
                             labels={'title': 'Award / achievement', 'organisation': 'Organisation', 'year': 'Year', 'description': 'Description'})
VolunteerForm = _item_form(VolunteerExperience, ['organisation', 'role', 'start_date', 'end_date', 'description'],
                           widgets={'organisation': _T(), 'role': _T(), 'start_date': _T('For example: Jan 2022'),
                                    'end_date': _T('For example: Dec 2023'), 'description': _A(3)},
                           labels={'organisation': 'Organisation', 'role': 'Role', 'start_date': 'Start date', 'end_date': 'End date',
                                   'description': 'Description'})
ReferenceForm = _item_form(ProfessionalReference, ['name', 'position', 'organisation', 'relationship', 'email', 'phone', 'authorise_contact'],
                           widgets={'name': _T(), 'position': _T(), 'organisation': _T(), 'relationship': _T(),
                                    'email': forms.EmailInput(attrs=CTL), 'phone': _T()},
                           labels={'name': 'Reference name', 'position': 'Position', 'organisation': 'Organisation',
                                   'relationship': 'Relationship to you', 'email': 'Email', 'phone': 'Phone',
                                   'authorise_contact': 'I authorise PezaJob to contact this reference when required'})

# key -> (model, form, heading, intro, add label, name of the field that must be filled)
ITEM_TYPES = {
    'experience': (WorkExperience, ExperienceForm, 'Work experience', 'Add your current and previous employment.', 'Add work experience'),
    'volunteer': (VolunteerExperience, VolunteerForm, 'Volunteer experience', 'Volunteer roles show initiative and community involvement.', 'Add volunteer experience'),
    'education': (Education, EducationForm, 'Education', 'Add your schools, colleges and universities.', 'Add qualification'),
    'certification': (Certification, CertificationForm, 'Professional certifications', 'Certificates and licences that back up your skills.', 'Add certification'),
    'membership': (Membership, MembershipForm, 'Professional memberships', 'Professional bodies and associations you belong to.', 'Add membership'),
    'language': (SpokenLanguage, LanguageForm, 'Languages', 'Languages you can work in.', 'Add language'),
    'project': (Project, ProjectForm, 'Projects and portfolio', 'Showcase important projects you have worked on.', 'Add project'),
    'achievement': (Achievement, AchievementForm, 'Awards and achievements', 'Awards and professional achievements.', 'Add achievement'),
    'reference': (ProfessionalReference, ReferenceForm, 'Professional references',
                  'Add people who can confirm your experience. Your references are never shown publicly. Companies must request them and you decide whether to share.', 'Add reference'),
}

SECTION_FORMS = {
    'basics': BasicsForm,
    'about': AboutForm,
    'skills': SkillsForm,
    'preferences': PreferencesForm,
    'cv': CvLinksForm,
    'privacy': PrivacyForm,
}
SECTION_ITEMS = {
    'experience': ['experience', 'volunteer'],
    'education': ['education', 'certification', 'membership'],
    'skills': ['language'],
    'cv': ['project', 'achievement'],
    'privacy': ['reference'],
}
