from django.contrib import admin
from django import forms
from django.utils.html import format_html
from django.urls import reverse
from .models import Classroom, Teacher, Subject, Resource, Student, City, Governorate, Package

class ActionsModelAdmin(admin.ModelAdmin):
    """
    Mixin to add an actions column to the admin list view.
    """
    def actions_column(self, obj):
        app_label = obj._meta.app_label
        model_name = obj._meta.model_name
        
        edit_url = reverse(f'admin:{app_label}_{model_name}_change', args=[obj.pk])
        delete_url = reverse(f'admin:{app_label}_{model_name}_delete', args=[obj.pk])
        
        return format_html(
            '<div style="white-space: nowrap;">'
            '<a class="btn btn-sm btn-primary" href="{}" title="تعديل" style="margin-right:5px;"><i class="fas fa-edit"></i></a>'
            '<a class="btn btn-sm btn-danger" href="{}" title="حذف"><i class="fas fa-trash-alt"></i></a>'
            '</div>',
            edit_url,
            delete_url
        )
    actions_column.short_description = 'إجراءات'

@admin.register(Classroom)
class ClassroomAdmin(ActionsModelAdmin):
    list_display = ('name_en', 'name_ar', 'actions_column')

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

@admin.register(Subject)
class SubjectAdmin(ActionsModelAdmin):
    list_display = ('name_en', 'name_ar', 'classroom', 'price', 'get_teachers', 'actions_column')
    list_filter = ('classroom', 'teachers')
    search_fields = ('name_en', 'name_ar')
    filter_horizontal = ('teachers',)

    def get_teachers(self, obj):
        return ", ".join([str(t) for t in obj.teachers.all()])
    get_teachers.short_description = 'المعلمون'

@admin.register(City)
class CityAdmin(ActionsModelAdmin):
    list_display = ('name_en', 'name_ar', 'governorate', 'actions_column')
    list_filter = ('governorate',)

@admin.register(Governorate)
class GovernorateAdmin(ActionsModelAdmin):
    list_display = ('name_en', 'name_ar', 'actions_column')

class ResourceAdminForm(forms.ModelForm):
    classroom = forms.ModelChoiceField(
        queryset=Classroom.objects.all(),
        required=True,
        label="تصفية حسب الصف"
    )

    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['classroom'].initial = self.instance.subject.classroom

@admin.register(Resource)
class ResourceAdmin(ActionsModelAdmin):
    form = ResourceAdminForm
    list_display = ('title_en', 'subject', 'resource_type', 'created_at', 'actions_column')
    list_filter = ('subject__classroom', 'subject', 'resource_type')
    fields = ('classroom', 'subject', 'title_en', 'title_ar', 'resource_type', 'file', 'link')
    
    class Media:
        js = ('js/admin_resource.js',)

@admin.register(Student)
class StudentAdmin(ActionsModelAdmin):
    list_display = ('user', 'classroom', 'mobile_number', 'city', 'governorate', 'actions_column')
    list_filter = ('classroom', 'city', 'governorate')
    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.classroom:
            form.base_fields['subscribed_subjects'].queryset = Subject.objects.filter(classroom=obj.classroom)
        return form

@admin.register(Package)
class PackageAdmin(ActionsModelAdmin):
    list_display = ('name_en', 'name_ar', 'classroom', 'price', 'is_active', 'actions_column')
    list_filter = ('classroom', 'is_active')
    list_editable = ('is_active',)
    filter_horizontal = ('subjects',)
    search_fields = ('name_en', 'name_ar')

    class Media:
        js = ('js/admin_package.js',)

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