from django import forms
from django.core.validators import FileExtensionValidator

from apps.standards.models import (
    StandardSource,
    StandardCategory,
    Standard,
    StandardCompliance,
    StandardAttachment,
    ActivityType,
)


class StandardSourceForm(forms.ModelForm):
    class Meta:
        model = StandardSource
        fields = ['name', 'name_ar', 'code', 'description', 'website', 'is_active']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 3}),
        }


class StandardCategoryForm(forms.ModelForm):
    class Meta:
        model = StandardCategory
        fields = ['name', 'name_ar', 'description', 'source', 'max_score', 'order', 'is_active']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 3}),
        }


class ActivityTypeForm(forms.ModelForm):
    class Meta:
        model = ActivityType
        fields = ['name', 'name_ar', 'description', 'is_active']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 3}),
        }


class StandardForm(forms.ModelForm):
    class Meta:
        model = Standard
        fields = ['source', 'category', 'code', 'title', 'title_ar', 'description',
                  'departments', 'activity_type', 'parent_standard', 'assessment_method', 'assessment_method_ar',
                  'order_within_category', 'is_heading', 'is_assessable',
                  'effective_date', 'review_date', 'is_active']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 5}),
            'effective_date': forms.DateInput(attrs={'type': 'date'}),
            'review_date': forms.DateInput(attrs={'type': 'date'}),
            'departments': forms.CheckboxSelectMultiple(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        source_id = None
        if self.instance and hasattr(self.instance, 'source_id') and self.instance.source_id:
            source_id = self.instance.source_id
        elif self.data.get('source'):
            source_id = self.data['source']

        if source_id:
            self.fields['category'].queryset = StandardCategory.objects.filter(
                source_id=source_id, is_active=True
            ).order_by("order", "name")
        else:
            self.fields['category'].queryset = StandardCategory.objects.none()

        self.fields['parent_standard'].queryset = Standard.objects.filter(
            is_active=True, parent_standard__isnull=True
        ).order_by("source", "code")
        if self.instance and self.instance.pk:
            self.fields['parent_standard'].queryset = self.fields['parent_standard'].queryset.exclude(pk=self.instance.pk)
        self.fields['parent_standard'].required = False
        self.fields['parent_standard'].widget.attrs.update({
            'class': 'form-select',
            'id': 'id_parent_standard',
        })


class StandardComplianceForm(forms.ModelForm):
    class Meta:
        model = StandardCompliance
        fields = ['hospital', 'department', 'standard', 'status', 'status_ar',
                  'last_assessed_date', 'assessor', 'notes', 'recommendations', 'evidence_summary',
                  'target_status', 'corrective_action', 'priority', 'target_date', 'target_date_actual',
                  'score', 'max_score', 'assessment_code', 'assessment_code_target',
                  'supporting_documents', 'action_note']
        widgets = {
            'last_assessed_date': forms.DateInput(attrs={'type': 'date'}),
            'target_date_actual': forms.DateInput(attrs={'type': 'date'}),
            'notes': forms.Textarea(attrs={'rows': 3}),
            'recommendations': forms.Textarea(attrs={'rows': 3}),
            'evidence_summary': forms.Textarea(attrs={'rows': 3}),
            'corrective_action': forms.Textarea(attrs={'rows': 3}),
            'supporting_documents': forms.Textarea(attrs={'rows': 3}),
            'action_note': forms.Textarea(attrs={'rows': 3}),
        }


class StandardAttachmentForm(forms.ModelForm):
    class Meta:
        model = StandardAttachment
        fields = ['file', 'description']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 2}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['file'].widget.attrs.update({
            'accept': '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.zip'
        })
