from django import forms
from .models import Feedback, FeedbackCategory

class VerificationForm(forms.Form):
    registration_code = forms.CharField(
        max_length=50,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter your registration code'
        })
    )

class FeedbackForm(forms.ModelForm):
    class Meta:
        model = Feedback
        fields = ['name', 'email', 'registration_code', 'category', 'rating', 'comment', 'is_anonymous']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Your name (optional if using registration code)'
            }),
            'email': forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': 'Your email (optional)'
            }),
            'registration_code': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Your registration code (if available)'
            }),
            'category': forms.Select(attrs={
                'class': 'form-select'
            }),
            'rating': forms.RadioSelect(attrs={
                'class': 'rating-input'
            }),
            'comment': forms.Textarea(attrs={
                'class': 'form-control',
                'placeholder': 'Please share your feedback here',
                'rows': 5
            }),
            'is_anonymous': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            })
        }
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].required = False
        self.fields['email'].required = False
        self.fields['registration_code'].required = False
        self.fields['category'].required = True
        self.fields['rating'].required = True
        self.fields['comment'].required = True
        self.fields['is_anonymous'].required = False
        self.fields['is_anonymous'].label = 'Submit anonymously'
        
        # Only show active categories
        self.fields['category'].queryset = FeedbackCategory.objects.filter(is_active=True)
        
    def clean(self):
        cleaned_data = super().clean()
        name = cleaned_data.get('name')
        email = cleaned_data.get('email')
        registration_code = cleaned_data.get('registration_code')
        is_anonymous = cleaned_data.get('is_anonymous')
        
        # If anonymous is not checked, require either name or registration code
        if not is_anonymous and not registration_code and not name:
            self.add_error('name', 'Please provide your name or registration code if not submitting anonymously')
            
        return cleaned_data
