from django import forms
from .models import FormField

# applicant/forms_builder.py
def create_dynamic_form(form_instance):
    fields = {}
    
    for field in form_instance.fields.all():
        field_kwargs = {
            'label': field.label,
            'required': field.required,
            'help_text': field.help_text
        }
        
        # Use stable field_name instead of database ID
        field_key = field.field_name
        
        if field.field_type == 'text':
            fields[field_key] = forms.CharField(**field_kwargs)
        elif field.field_type == 'email':
            fields[field_key] = forms.EmailField(**field_kwargs)
        elif field.field_type == 'phone':
            fields[field_key] = forms.CharField(**field_kwargs)
        elif field.field_type == 'number':
            fields[field_key] = forms.IntegerField(**field_kwargs)
        elif field.field_type == 'date':
            fields[field_key] = forms.DateField(**field_kwargs)
        elif field.field_type == 'textarea':
            fields[field_key] = forms.CharField(
                widget=forms.Textarea,
                **field_kwargs
            )
        elif field.field_type in ['select', 'radio']:
            choices = [(c.strip(), c.strip()) for c in field.choices.split(',') if c.strip()]
            if not choices:
                choices = [('', '---')]
            if field.field_type == 'select':
                fields[field_key] = forms.ChoiceField(choices=choices, **field_kwargs)
            else:
                fields[field_key] = forms.ChoiceField(
                    choices=choices,
                    widget=forms.RadioSelect,
                    **field_kwargs
                )
        elif field.field_type == 'checkbox':
            field_kwargs['required'] = False
            fields[field_key] = forms.BooleanField(**field_kwargs)
    
    return type('DynamicApplicantForm', (forms.Form,), fields)