from xml.dom import Node
import django_filters
from django.db.models import Max, F, Q
from django.contrib.auth import get_user_model
from django.contrib import admin
from django.utils import timezone

from dateutil.relativedelta import relativedelta

from .models import Activity, Prospect, Status, DeclinationReason, ProspectGroup

User = get_user_model()

class ProspectFilter(django_filters.FilterSet):
    zip_code = django_filters.CharFilter(lookup_expr='istartswith', label='Code postal')
    activities = django_filters.ModelMultipleChoiceFilter(
        queryset=Activity.objects.all(),
        field_name='activities',
    )
    city = django_filters.CharFilter(lookup_expr='icontains', label='Ville')
    name = django_filters.CharFilter(method='filter_name', label='Nom')

    def filter_name(self, queryset, name, value):
        return queryset.filter(
            Q(first_name__icontains=value) | Q(last_name__icontains=value) | Q(entity_name__icontains=value)
        )

    class Meta:
        model = Prospect
        fields = ['name', 'city', 'activities', 'zip_code']

class StaffUserFilter(admin.SimpleListFilter):
    title = 'staff user'
    parameter_name = 'user'

    def lookups(self, request, model_admin):
        staff_users = User.objects.filter(is_staff=True)
        return [(user.id, user.username) for user in staff_users]

    def queryset(self, request, queryset):
        # Filter the queryset based on the selected user ID
        if self.value():
            return queryset.filter(related_user__id=self.value())
        return queryset

class ProspectProfileFilter(admin.SimpleListFilter):
    title = 'Prospect profiles'  # displayed in the admin UI
    parameter_name = 'profile'    # URL parameter

    def lookups(self, request, model_admin):
        return (
            ('tournament_at_least_1_month_old', 'tournaments > 1 month old'),
            ('no_tournaments', 'No tournaments'),
        )

    def queryset(self, request, queryset):
        if not self.value():
            return queryset

        two_months_ago = timezone.now().date() - relativedelta(months=2)

        if self.value() == 'tournament_at_least_2_month_old':
            return queryset.filter(
                official_user__isnull=False,
                official_user__events__creation_date__lte=two_months_ago
            )
        elif self.value() == 'no_tournaments':
            return queryset.filter(
                official_user__isnull=False,
                official_user__events__isnull=True
            )

class ProspectStatusFilter(admin.SimpleListFilter):
    title = 'Status'
    parameter_name = 'status'

    def lookups(self, request, model_admin):
        return [(tag.name, tag.value) for tag in Status]

    def queryset(self, request, queryset):
        if self.value() == Status.NONE:
            return queryset.filter(activities__isnull=True)
        elif self.value():
            prospects_with_status = []
            for prospect in queryset:
                if prospect.current_status() == self.value():
                    prospects_with_status.append(prospect.id)
            return queryset.filter(id__in=prospects_with_status)
        else:
            return queryset

class ProspectDeclineReasonFilter(admin.SimpleListFilter):
    title = 'Decline reason'
    parameter_name = 'reason'

    def lookups(self, request, model_admin):
        return [(tag.name, tag.value) for tag in DeclinationReason]

    def queryset(self, request, queryset):
        if self.value():
            # Get prospects whose most recent activity has the selected status
            return queryset.filter(
                activities__declination_reason=self.value()
            ).annotate(
                latest_activity_date=Max('activities__creation_date')
            ).filter(
                activities__creation_date=F('latest_activity_date'),
                activities__declination_reason=self.value()
            ).distinct()
        else:
            return queryset

class ProspectGroupFilter(admin.SimpleListFilter):
    title = 'ProspectGroup'
    parameter_name = 'prospect_group'

    def lookups(self, request, model_admin):
        prospect_groups = ProspectGroup.objects.all().order_by('-creation_date')
        return [(group.id, group.name) for group in prospect_groups]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(prospect_groups__id=self.value())
        return queryset

class ContactAgainFilter(admin.SimpleListFilter):
    title = 'Contact again'  # or whatever you want
    parameter_name = 'contact_again'

    def lookups(self, request, model_admin):
        return (
            ('1', 'Should be contacted'),
            # ('0', 'Is null'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            return queryset.filter(contact_again__isnull=False)
        # if self.value() == '0':
        #     return queryset.filter(my_field__isnull=True)
        return queryset

class PhoneFilter(admin.SimpleListFilter):
    title = 'Phone number'
    parameter_name = 'phone_filter'

    def lookups(self, request, model_admin):
        return (
            ('exclude_mobile', 'Exclude mobile (06/07)'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'exclude_mobile':
            return queryset.exclude(
                Q(phone__startswith='06') | Q(phone__startswith='07')
            )
        return queryset
