from django import forms
from django.db import models
from django.utils.translation import gettext_lazy as _

from wagtail.admin.forms.choosers import BaseFilterForm


class AccountChooseFilterForm(BaseFilterForm):
    q = forms.CharField(
        label=_("Search term"),
        widget=forms.TextInput(attrs={"placeholder": _("Search")}),
        required=False,
    )

    def filter(self, objects):
        objects = super().filter(objects)
        search_query = self.cleaned_data.get("q")
        if search_query:
            objects = objects.filter(
                models.Q(username__icontains=search_query)
                | models.Q(first_name__icontains=search_query)
                | models.Q(last_name__icontains=search_query)
                | models.Q(email__icontains=search_query)
            )
            self.is_searching = True
            self.search_query = search_query

        return objects
