(function($) {
    'use strict';
    $(function() {
        console.log("Admin Package JS loaded");

        var $levelSelect = $('#id_classroom');
        var $subjectSelect = $('#id_subjects');
        
        // Debug selector finding
        if (!$levelSelect.length) console.error("Classroom select #id_classroom not found!");
        if (!$subjectSelect.length) console.error("Subjects select #id_subjects not found!");

        // Check if we are in the admin change form
        if (!$levelSelect.length || !$subjectSelect.length) return;

        var isArabic = $('html').attr('lang') === 'ar' || $('body').hasClass('rtl');

        function updateSubjects(levelId, selectedValues) {
            console.log("Updating subjects for level:", levelId);

            if (!levelId) {
                $subjectSelect.html('');
                refreshSelectFilter();
                return;
            }

            $.getJSON('/ajax/get-subjects-by-level/', {level_id: levelId}, function(data) {
                console.log("Received subjects:", data);
                var options = '';
                $.each(data, function(index, subject) {
                    var selected = '';
                    if (selectedValues && selectedValues.indexOf(subject.id.toString()) !== -1) {
                        selected = ' selected';
                    }
                    var name = isArabic ? subject.name_ar : subject.name_en;
                    options += '<option value="' + subject.id + '"' + selected + '>' + name + '</option>';
                });
                $subjectSelect.html(options);
                refreshSelectFilter();
            })
            .fail(function(jqxhr, textStatus, error) {
                console.error("AJAX Error:", textStatus, error);
            });
        }

        function refreshSelectFilter() {
            var fieldName = 'subjects';
            // Django's filter_horizontal uses SelectFilter2
            if (typeof SelectFilter2 !== 'undefined') {
                console.log("Refreshing SelectFilter2");
                // Remove the existing widget elements
                $('.selector').has('#id_' + fieldName + '_from').remove();
                
                // Re-initialize it
                SelectFilter2.init('id_' + fieldName, fieldName, false);
            } else if (typeof SelectFilter !== 'undefined') {
                 console.log("Refreshing SelectFilter (Legacy)");
                $('.selector').has('#id_' + fieldName + '_from').remove();
                SelectFilter.init('id_' + fieldName, fieldName, false);
            } else {
                console.warn("SelectFilter not found!");
            }
        }

        $levelSelect.on('change', function() {
            console.log("Classroom changed to:", $(this).val());
            var selectedValues = [];
            // Reset subjects when classroom changes
            updateSubjects($(this).val(), []);
        });

        // If we are editing an existing package
        if ($levelSelect.val()) {
            console.log("Initial load with classroom:", $levelSelect.val());
            // Get currently selected values
            var selectedValues = [];
            
            // Try to get from the "chosen" side of filter_horizontal if it exists
            // Since this runs on page load, standard Django might have already rendered the widget
            $('#id_subjects_to option').each(function() {
                selectedValues.push($(this).val());
            });
            
            // Fallback if widget not yet initialized or for simple select
            if (selectedValues.length === 0) {
                $subjectSelect.find('option:selected').each(function() {
                    selectedValues.push($(this).val());
                });
            }
            
            console.log("Initial selected values:", selectedValues);
            updateSubjects($levelSelect.val(), selectedValues);
        }
    });
})(django.jQuery);