from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView
from django.contrib.messages.views import SuccessMessageMixin
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import UpdateView
from django.views.generic.edit import CreateView
from django.contrib.auth import login
from .forms import RegistrationForm, LoginForm, OrganizationForm, UserProfileForm
from .mixins import TenantOwnerRequiredMixin
from .models import Organization, Membership, UserProfile


class RegisterView(CreateView):
    template_name = 'register/register.html'
    form_class = RegistrationForm
    success_url = reverse_lazy('login')

    def form_valid(self, form):
        user = form.save()
        company_name = form.cleaned_data.get('company_name')
        org = Organization.objects.create(name=company_name)
        Membership.objects.create(
            user=user,
            organization=org,
            role='owner'
        )
        login(self.request, user)

        return redirect(self.success_url)

class CustomLoginView(LoginView):
    template_name = 'account/login.html'
    authentication_form = LoginForm
    redirect_authenticated_user = True # Als ze al ingelogd zijn, stuur ze door naar core

class SelectOrganizationView(LoginRequiredMixin, View):
    def get(self, request):
        memberships = request.user.memberships.select_related('organization').all()

        if memberships.count() == 1:
            request.session['active_org_id'] = str(memberships.first().organization.id)
            return redirect('dashboard')

        return render(request, 'account/select_organization.html', {
            'memberships': memberships
        })

    def post(self, request):
        org_id = request.POST.get('org_id')
        request.session['active_org_id'] = org_id
        return redirect('dashboard')

class UserProfileView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = UserProfile
    form_class = UserProfileForm
    template_name = 'account/profile.html'
    success_url = reverse_lazy('user_profile')
    success_message = "Je persoonlijke gegevens zijn bijgewerkt!"

    def get_object(self, queryset=None):
        return self.request.user.profile

class CompanySettingsView(TenantOwnerRequiredMixin, LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Organization
    form_class = OrganizationForm  # Gebruik nu het formulier
    template_name = 'account/company_settings.html'
    success_url = reverse_lazy('company_settings')
    success_message = "Bedrijfsnaam is succesvol aangepast!"

    def get_object(self, queryset=None):
        return self.request.organization
