from django.http import JsonResponse
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.decorators import login_required
from django.views import View
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic import ListView, DetailView, TemplateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import transaction
from django.contrib import messages
from datetime import datetime, timezone
from django.utils.timezone import now
from core.utils import get_registration_year, season_getter
from core.views import ClubRequiredMixin
from players.models import Player
from .models import Club, Official
from core.models import User
from .forms import ClubForm, ResubmitClubForm
from .models import Official
from .forms import OfficialForm


@login_required()
def update_official_status(request, pk):
    if request.method == "POST":
        action = request.POST.get("action")
        if action not in ["Approved", "Rejected"]:
            return JsonResponse({"message": "Invalid status"}, status=400)

        official = get_object_or_404(Official, pk=pk)
        official.status = action
        official.save()
        return redirect("official_detail", pk=pk)


@login_required()
def official_create(request):
    coach_fields = ['coaching_certificate_obtained',
                    'certificate_year', 'certificate_upload']
    form = OfficialForm(request.POST or None, request.FILES or None)

    if request.method == 'POST':
        if form.is_valid():
            official = form.save(commit=False)
            club = get_object_or_404(Club, user=request.user)
            official.club = club
            official.save()
            return redirect('club_official_list')

    return render(request, 'officials/form.html', {
        'form': form,
        'title': 'Register Official',
        'coach_fields': coach_fields,
    })


@login_required()
def official_update(request, pk):
    official = get_object_or_404(Official, pk=pk)
    coach_fields = ['coaching_certificate_obtained',
                    'certificate_year', 'certificate_upload']

    if request.method == 'POST':
        form = OfficialForm(request.POST, request.FILES, instance=official)
        if form.is_valid():
            form.save()
            # or use named URL
            return redirect(f'club_official_list?status={official.status}')
    else:
        form = OfficialForm(instance=official)

    return render(request, 'officials/form.html', {
        'form': form,
        'title': 'Update Official',
        'coach_fields': coach_fields,
    })


@login_required()
def official_detail(request, pk):
    official = get_object_or_404(Official, pk=pk)
    return render(request, 'officials/detail.html', {'official': official})


@login_required()
def official_delete(request, pk):
    official = get_object_or_404(Official, pk=pk)
    if request.method == 'POST':
        official.delete()
        return redirect('official_list')
    return render(request, 'officials/confirm_delete.html', {'official': official})


class ClubDashboardView(LoginRequiredMixin, ClubRequiredMixin, TemplateView):
    template_name = "club/index.html"
    model = Club

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        active_season = season_getter()

        club = get_object_or_404(
            Club, user=self.request.user, season=active_season)

        # Calculate days remaining
        today = now().date()
        deadline = active_season.registration_end
        days_remaining = (deadline - today).days

        context["msg"] = "Dashboard"
        context["club_status"] = club.status
        context["club"] = club
        context["season"] = active_season
        context["days_remaining"] = days_remaining
        return context


class ClubOfficialHomeView(LoginRequiredMixin, ClubRequiredMixin, TemplateView):
    model = Official
    template_name = "club/official_home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        active_season = season_getter()

        club = get_object_or_404(Club, user=self.request.user, season=active_season)

        context["msg"] = "Officials Page"
        context["club_id"] = club.id
        context["club"] = club
        return context


# Officials
class ClubOfficialsView(LoginRequiredMixin, ClubRequiredMixin, ListView):
    model = Official
    template_name = "club/official_list.html"
    context_object_name = "official_list"

    def get_queryset(self):
        club_id = get_object_or_404(Club, user=self.request.user)
        status_filter = self.request.GET.get("status")

        queryset = Official.objects.filter(club_id=club_id)

        if status_filter:
            queryset = queryset.filter(status=status_filter)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["status_filter"] = self.request.GET.get("status", "")
        return context


class ClubRegistration(CreateView):
    model = Club
    form_class = ClubForm
    template_name = "club/create.club.html"
    success_url = reverse_lazy('login_page')

    def form_valid(self, form):
        club = form.save(commit=False)
        
        club_data = form.cleaned_data
        email = club_data['email']
        username = club_data['username']

        if User.objects.filter(email=email).exists():
            messages.error(self.request, "This email is already registered with a club.")
            return self.form_invalid(form)

        if User.objects.filter(username=username).exists():
            messages.error(self.request, "This username is already taken.")
            return self.form_invalid(form)

        try:
            with transaction.atomic():
                user = User.objects.create_user(
                    username=username,
                    email=email,
                    password=club_data['password'],
                    club_name=club_data['club_name'],
                    club_logo=club_data['club_logo'],
                    role='club'
                )

                club.user = user
                club.reg_year = get_registration_year()
                club.season = season_getter()
                club.save()

            messages.success(self.request, "Club registered successfully!")
            return super().form_valid(form)

        except Exception as e:
            messages.error(self.request, f"Unexpected error: {str(e)}")
            return self.form_invalid(form)
        
        

class ClubResubmitView(LoginRequiredMixin, UpdateView):
    model = Club
    form_class = ResubmitClubForm
    context_object_name = "club" 
    template_name = "club/resubmit.club.html"
    success_url = reverse_lazy("club_dashboard")
    
    # def get(self, request, *args, **kwargs):
    #     return super().get(request, *args, **kwargs)
      
    def get_object(self, queryset=None):
        return get_object_or_404(Club, user=self.request.user)

    def form_valid(self, form):
        club = form.save(commit=False)

        # Reset status to Unapproved when resubmitting
        if club.status == "Rejected":
            club.status = "Unapproved"
            club.rejection_message = ""  

        club.save()
        messages.success(self.request, "Your club data has been updated and resubmitted for approval.")
        return super().form_valid(form)

    def form_invalid(self, form):
        messages.error(self.request, "Please correct the errors below.")
        return super().form_invalid(form)




class GetPlayersByClubByStatusView(LoginRequiredMixin, ClubRequiredMixin, ListView):
    model = Player
    template_name = "club_players_by_status.html"
    context_object_name = "players"
    expected_status = ["Unapproved", "Approved"]

    def get_queryset(self):
        club_id = self.request.user
        status = self.request.GET.get("status")

        active_season = season_getter()

        if status not in self.expected_status:
            return Player.objects.none()

        return Player.objects.get(club_id=club_id, status=status, Season=active_season, reg_year=datetime.now().year)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["msg"] = "Club Players List"
        return context
