from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone

from .context_processors import CLUBS
from .forms import LoginForm, RegistrationForm
from .models import MembershipPlan, Subscription


def home(request):
    plans = MembershipPlan.objects.all()
    return render(request, "home.html", {"plans": plans, "clubs": CLUBS})


def register_view(request):
    if request.user.is_authenticated:
        return redirect("dashboard")

    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, "Добро пожаловать в клуб!")
            return redirect("dashboard")
        messages.error(request, "Исправьте ошибки в форме.")
    else:
        form = RegistrationForm()
    return render(request, "register.html", {"form": form})


def login_view(request):
    if request.user.is_authenticated:
        return redirect("dashboard")

    if request.method == "POST":
        form = LoginForm(request=request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            messages.success(request, "С возвращением!")
            return redirect("dashboard")
        messages.error(request, "Неверный логин или пароль")
    else:
        form = LoginForm()
    return render(request, "login.html", {"form": form})


def logout_view(request):
    logout(request)
    messages.info(request, "Вы вышли из аккаунта")
    return redirect("home")


@login_required
def dashboard(request):
    today = timezone.now().date()
    active_subscription = (
        Subscription.objects.filter(user=request.user, end_date__gte=today)
        .order_by("-end_date")
        .first()
    )
    history = Subscription.objects.filter(user=request.user).order_by("-start_date")
    plans = MembershipPlan.objects.all()
    return render(
        request,
        "dashboard.html",
        {
            "active_subscription": active_subscription,
            "history": history,
            "plans": plans,
        },
    )


@login_required
def subscribe(request, plan_id):
    if request.method != "POST":
        messages.error(request, "Неверный метод запроса")
        return redirect("dashboard")

    plan = get_object_or_404(MembershipPlan, id=plan_id)
    subscription = Subscription.create_for_plan(request.user, plan)
    messages.success(
        request,
        f"Вы оформили '{plan.name}' до {subscription.end_date.strftime('%d.%m.%Y')}.",
    )
    return redirect("dashboard")
