from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.views.generic import ListView, DetailView, UpdateView
from django.utils.decorators import method_decorator
from django.urls import reverse_lazy
from .forms import ProfileEditForm

User = get_user_model()

def is_admin_or_user_manager(user):
    """Check if user is admin or has user management permission"""
    return user.is_superuser or user.has_user_management_permission

@login_required
def profile(request):
    """User profile view"""
    return render(request, 'users/profile.html')

@login_required
def profile_edit(request):
    """Edit user profile"""
    if request.method == 'POST':
        form = ProfileEditForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, 'Profile updated successfully!')
            return redirect('users:profile')
    else:
        form = ProfileEditForm(instance=request.user)
    
    return render(request, 'users/profile_edit.html', {'form': form})

@method_decorator(login_required, name='dispatch')
@method_decorator(user_passes_test(is_admin_or_user_manager), name='dispatch')
class UserListView(ListView):
    """List all users (admin and user managers only)"""
    model = User
    template_name = 'users/user_list.html'
    context_object_name = 'users'
    paginate_by = 20
    
    def get_queryset(self):
        return User.objects.all().order_by('username')

@method_decorator(login_required, name='dispatch')
@method_decorator(user_passes_test(is_admin_or_user_manager), name='dispatch')
class UserDetailView(DetailView):
    """User detail view (admin and user managers only)"""
    model = User
    template_name = 'users/user_detail.html'
    context_object_name = 'user_obj'
