from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.mixins import AccessMixin
from django.urls import reverse_lazy
from django.views import View


# def club_login(request):
#     return render(request, "registration/login.html")

class LandingPageView(View):
    template_name = "landing.html"

    def get(self, request):
        return render(request, self.template_name)
    

class ClubLoginView(View):
    template_name = "registration/login.html"

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request):
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)

        if user is not None and user.role == "club":
            login(request, user)
            messages.success(request, "Welcome back!")
            return redirect("club_dashboard")
        else:
            error = "Invalid credentials or unauthorized access."
            return render(request, self.template_name, {"error": error})


class ClubRequiredMixin(AccessMixin):
    """Mixin that requires the user to be logged in and a club member."""

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            error = {"error": "You must be logged in to access this page."}
            return redirect("admin_login", {"error": error})

        if not request.user.role == "club":
            return redirect("forbidden_page")

        return super().dispatch(request, *args, **kwargs)


class ForbiddenPageView(View):
    template_name = "forbidden.html"

    def get(self, request):
        return render(request, self.template_name)


class LogoutView(View):
    def get(self, request):
        logout(request)
        return redirect("login_page")
