from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import reverse_lazy
from django.views.generic import CreateView, FormView

from .forms import ClientLoginForm, ClientProfileForm, SignUpForm
from .models import ClientProfile


class SignUpView(CreateView):
    form_class = SignUpForm
    template_name = "accounts/signup.html"
    success_url = reverse_lazy("projects:dashboard")

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return self.redirect_authenticated()
        return super().dispatch(request, *args, **kwargs)

    def redirect_authenticated(self):
        from django.shortcuts import redirect

        return redirect("projects:dashboard")

    def form_valid(self, form):
        response = super().form_valid(form)
        login(self.request, self.object, backend="django.contrib.auth.backends.ModelBackend")
        messages.success(self.request, "Welcome! Your client account is ready.")
        return response


class ClientLoginView(LoginView):
    form_class = ClientLoginForm
    template_name = "accounts/login.html"
    redirect_authenticated_user = True

    def get_success_url(self):
        return self.request.GET.get("next") or reverse_lazy("projects:dashboard")


class ClientLogoutView(LogoutView):
    next_page = reverse_lazy("pages:home")
    http_method_names = ["post", "options"]

    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        if request.method.lower() == "post":
            messages.success(request, "You have been logged out.")
        return response


class ProfileView(LoginRequiredMixin, FormView):
    form_class = ClientProfileForm
    template_name = "accounts/profile.html"
    success_url = reverse_lazy("accounts:profile")

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["user"] = self.request.user
        profile, _ = ClientProfile.objects.get_or_create(user=self.request.user)
        kwargs["instance"] = profile
        return kwargs

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        profile, _ = ClientProfile.objects.get_or_create(user=self.request.user)
        ctx["profile"] = profile
        return ctx

    def form_valid(self, form):
        form.save()
        messages.success(self.request, "Profile updated.")
        return super().form_valid(form)
