from django.contrib import admin
from django import forms
from .models import EducationalLevel, Teacher, Subject, Resource, Student

@admin.register(EducationalLevel)
class EducationalLevelAdmin(admin.ModelAdmin):
    list_display = ('name_en', 'name_ar')

@admin.register(Teacher)
class TeacherAdmin(admin.ModelAdmin):
    list_display = ('user', 'specialization')

@admin.register(Subject)
class SubjectAdmin(admin.ModelAdmin):
    list_display = ('name_en', 'name_ar', 'level', 'price', 'teacher')
    list_filter = ('level', 'teacher')
    search_fields = ('name_en', 'name_ar')

class ResourceAdminForm(forms.ModelForm):
    educational_level = forms.ModelChoiceField(
        queryset=EducationalLevel.objects.all(),
        required=True,
        label="Filter by Educational Level"
    )

    class Meta:
        model = Resource
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk and self.instance.subject:
            self.fields['educational_level'].initial = self.instance.subject.level

@admin.register(Resource)
class ResourceAdmin(admin.ModelAdmin):
    form = ResourceAdminForm
    list_display = ('title_en', 'subject', 'created_at')
    list_filter = ('subject__level', 'subject')
    fields = ('educational_level', 'subject', 'title_en', 'title_ar', 'file', 'link')
    
    class Media:
        js = ('js/admin_resource.js',)

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    list_display = ('user', 'level', 'phone_number')
    list_filter = ('level',)
    filter_horizontal = ('subscribed_subjects',)
    
    class Media:
        js = ('js/admin_student.js',)

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if obj and obj.level:
            form.base_fields['subscribed_subjects'].queryset = Subject.objects.filter(level=obj.level)
        return form