# views.py
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from .forms import CustomLoginForm, CustomUserCreationForm, UserProfileForm, UserCustomForm
from .models import UserProfile
from .filters import UserFilter
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from core.utils import ConfigurableCRUDView
from django.contrib.auth.models import User
from django.db.models import F
from types import SimpleNamespace

def login_view(request):
    if request.method == "POST":
        form = CustomLoginForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('dashboard:index')  # Redirect to your dashboard
    else:
        form = CustomLoginForm()

    return render(request, 'auth/login.html', {'form': form, 'hide_sidebar': True})

def register_view(request):
    if request.method == "POST":
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)  # Log the user in after creation
            return redirect('dashboard:index')  # Redirect to your dashboard
    else:
        form = CustomUserCreationForm()

    return render(request, 'auth/register.html', {'form': form, 'hide_sidebar': True})

def logout_view(request):
    logout(request)  # Logs out the user
    return redirect('sysadmin:login')  # Redirect to the login page after logout

@login_required
def profile_view(request):
    try:
        # Get the profile for the current user
        profile = request.user.profile
    except UserProfile.DoesNotExist:
        # Create a profile if it doesn't exist
        profile = UserProfile.objects.create(user=request.user)

    if request.method == "POST":
        form = UserProfileForm(request.POST, request.FILES, instance=profile)

        user = request.user
        user.first_name = request.POST.get('first_name', user.first_name)
        user.last_name = request.POST.get('last_name', user.last_name)

        if form.is_valid():
            form.save()
            user.save()
            messages.success(request, "Profile Updated")
            return redirect('sysadmin:profile')  # Redirect to the profile page after saving
        else:
            messages.error(request, form.errors)
    else:
        form = UserProfileForm(instance=profile)

    return render(request, 'sysadmin/profile.html', {'form': form})


class UserCRUDView(ConfigurableCRUDView):
    model = User
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'sysadmin/user_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = UserFilter

    page_title = "Users"

    # URL name mappings
    list_url_name = 'sysadmin:users-list'
    create_url_name = 'sysadmin:users-create'
    update_url_name = 'sysadmin:users-update'
    delete_url_name = 'sysadmin:users-delete'
    # excludes = ["splitdata"]
    config_fields = ("id", "username", "is_active", "is_staff", "is_superuser", "last_login")
    config_field_orders = ["id",]  # Display these fields first
    form_class = UserCustomForm
    config_edit_fields = None
    ordering = ["-id"]

    def get_list_view(self):
        ViewClass = super().get_list_view()
        outer = self

        class UserListView(ViewClass):
            def get_queryset(self):
                qs = super().get_queryset()
                return qs.select_related('profile').annotate(
                    qa2_default=F('profile__qa2_default')
                )

            def get_context_data(self, **kwargs):
                context = super().get_context_data(**kwargs)
                qa2_field = SimpleNamespace(name='qa2_default', verbose_name='QA.2 Default')
                fields = list(context['fields'])
                idx = next((i for i, f in enumerate(fields) if f.name == 'is_superuser'), len(fields) - 1)
                fields.insert(idx + 1, qa2_field)
                context['fields'] = fields
                return context

        return UserListView
