# Django imports
from django.contrib.admin.filters import ChoicesFieldListFilter
from django.forms import Media


class PopupCompatibleMultiSelectRelatedDropdownFilter(ChoicesFieldListFilter):
    """
    A custom filter that maintains popup context when used in raw_id_fields modals.
    """
    
    def __init__(self, field, request, params, model, model_admin, field_path):
        super().__init__(field, request, params, model, model_admin, field_path)
        
        # Check if we're in a popup context
        self.is_popup = '_popup' in request.GET or 'pop' in request.GET or 'admin' not in request.path
        
        # Get all choices (related objects)
        self.lookup_choices = field.get_choices(include_blank=False)
        
    def has_output(self):
        return len(self.lookup_choices) > 1

    def value(self):
        return self.lookup_val

    def expected_parameters(self):
        return [self.lookup_kwarg, self.lookup_kwarg_isnull]

    def choices(self, changelist):
        # If in popup, preserve the popup parameters in the filter URL
        popup_params = {}
        if self.is_popup:
            # Preserve popup parameters
            if '_popup' in changelist.params:
                popup_params['_popup'] = 1
            if 'pop' in changelist.params:
                popup_params['pop'] = changelist.params['pop']
            if '_to_field' in changelist.params:
                popup_params['_to_field'] = changelist.params['_to_field']
        
        # Create the base URL with popup parameters
        all_params = changelist.get_filters_params()
        all_params.update(popup_params)
        
        # Generate the URL for the filter
        url = changelist.get_query_string(all_params, [self.lookup_kwarg])
        
        yield {
            'selected': self.lookup_val is None,
            'query_string': url,
            'display': 'All',
        }
        
        # Add choices
        for lookup, title in self.lookup_choices:
            params = dict(all_params)
            params[self.lookup_kwarg] = lookup
            
            # Remove the parameter if it's being set to the same value (for unselecting)
            if self.lookup_val == str(lookup):
                params.pop(self.lookup_kwarg, None)
            
            # Add popup parameters to each choice URL
            choice_params = params.copy()
            choice_params.update(popup_params)
            
            yield {
                'selected': str(lookup) == self.lookup_val,
                'query_string': changelist.get_query_string(choice_params, [self.lookup_kwarg_isnull]),
                'display': title,
            }

    @property
    def media(self):
        # Include necessary CSS/JS for dropdown functionality if needed
        return Media()