from django.contrib import admin
from .models import Club, TeamScore, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamRegistration, PlayerRegistration, Purchase, Court, DateInterval, FailedApiCall
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from datetime import timedelta
import uuid
from enum import Enum

class SimpleTournamentListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _("tournoi")

    # Parameter for the filter that will be used in the URL query.
    parameter_name = "tournament"

    def lookups(self, request, model_admin):
        tournaments = Tournament.objects.order_by('-start_date')
        return [(t.id, t.filter_name()) for t in tournaments]

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

class TeamScoreTournamentListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _("tournoi")

    # Parameter for the filter that will be used in the URL query.
    parameter_name = "tournament"

    def lookups(self, request, model_admin):
        tournaments = Tournament.objects.order_by('-start_date')
        return [(t.id, t.filter_name()) for t in tournaments]

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

class MatchTournamentListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _("tournoi")

    # Parameter for the filter that will be used in the URL query.
    parameter_name = "tournament"

    def lookups(self, request, model_admin):
        tournaments = Tournament.objects.order_by('-start_date')
        return [(t.id, t.filter_name()) for t in tournaments]

    def queryset(self, request, queryset):
        if self.value():
            query_round = Q(round__tournament__id=self.value())
            query_group_stage = Q(group_stage__tournament__id=self.value())
            return queryset.filter(query_round | query_group_stage)
        else:
            return queryset

class MatchType(Enum):
    GROUP_STAGE = 'Poule'
    BRACKET = 'Tableau'

class MatchTypeListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _("Type")

    # Parameter for the filter that will be used in the URL query.
    parameter_name = "name"

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

    def queryset(self, request, queryset):
        if self.value() == MatchType.GROUP_STAGE.name:
            return queryset.filter(group_stage__isnull=False)
        elif self.value() == MatchType.BRACKET.name:
            return queryset.filter(round__isnull=False)
        else:
            return queryset

class SimpleIndexListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _("Index")

    # Parameter for the filter that will be used in the URL query.
    parameter_name = "index"

    def lookups(self, request, model_admin):
        indexes = Match.objects.values_list('index', flat=True).distinct()
        return [(i, i) for i in sorted(indexes)]

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

class StartDateRangeFilter(admin.SimpleListFilter):
    title = 'tournament time range'  # displayed in the admin UI
    parameter_name = 'date_range'    # URL parameter

    def lookups(self, request, model_admin):
        return (
            ('upcoming', 'Next 30 days'),
            ('recent', 'Last 30 days'),
            ('current', 'Current (±3 days)'),
        )

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

        today = timezone.now().date()

        if self.value() == 'upcoming':
            return queryset.filter(
                start_date__gte=today,
                start_date__lte=today + timedelta(days=30)
            )
        elif self.value() == 'recent':
            return queryset.filter(
                start_date__gte=today - timedelta(days=30),
                start_date__lte=today
            )
        elif self.value() == 'current':
            return queryset.filter(
                start_date__gte=today - timedelta(days=3),
                start_date__lte=today + timedelta(days=3)
            )
