from django.contrib.auth import get_user_model
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views import generic

from .models import UserRole, Department
from .management_forms import UserForm

User = get_user_model()

class UserListView(LoginRequiredMixin, UserPassesTestMixin, generic.ListView):
    model = User
    template_name = 'users/user_list.html'
    context_object_name = 'users'
    paginate_by = 10
    
    def test_func(self):
        return self.request.user.is_staff


class UserDetailView(LoginRequiredMixin, UserPassesTestMixin, generic.DetailView):
    model = User
    template_name = 'users/user_detail.html'
    context_object_name = 'user'
    
    def test_func(self):
        return self.request.user.is_staff or self.request.user == self.get_object()

class UserCreateView(LoginRequiredMixin, UserPassesTestMixin, generic.CreateView):
    model = User
    form_class = UserForm
    template_name = 'users/user_form.html'
    success_url = reverse_lazy('users:user_list')
    
    def get_form_class(self):
        # Use MinisterUserForm for head of section creation
        role_type = self.request.GET.get('role')
        if role_type == 'head' and hasattr(self.request.user, 'department') and self.request.user.department:
            return MinisterUserForm
        return super().get_form_class()
    
    def get_template_names(self):
        # Use different template for head of section creation
        if self.request.GET.get('role') == 'head':
            return ['users/add_head.html']
        return super().get_template_names()
    
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        role_type = self.request.GET.get('role')
        if role_type == 'head' and hasattr(self.request.user, 'department') and self.request.user.department:
            kwargs['request'] = self.request
            kwargs['role_type'] = 'head'
        return kwargs
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        role_type = self.request.GET.get('role')
        if role_type == 'head':
            context['title'] = 'Add Head of Section'
        else:
            context['title'] = 'Add User'
        return context
    
    def test_func(self):
        # Only allow staff or users with department (like Director General) to create users
        return self.request.user.is_staff or hasattr(self.request.user, 'department')
    
    def get_success_url(self):
        # Redirect back to director dashboard after adding head of section
        if self.request.GET.get('role') == 'head':
            return reverse_lazy('dashboards:director')
        return super().get_success_url()
    
    def form_valid(self, form):
        role_type = self.request.GET.get('role')
        
        # For head of section creation
        if role_type == 'head':
            # The MinisterUserForm handles most of the logic
            if not hasattr(self.request.user, 'department') or not self.request.user.department:
                messages.error(self.request, 'You must be assigned to a department to create a head of section.')
                return self.form_invalid(form)
                
            # Ensure the department is under the director's department
            if 'department' in form.cleaned_data and form.cleaned_data['department']:
                if form.cleaned_data['department'].parent != self.request.user.department:
                    messages.error(self.request, 'You can only assign heads to sections under your department.')
                    return self.form_invalid(form)
        
        response = super().form_valid(form)
        
        # Set appropriate success message
        if role_type == 'head':
            messages.success(self.request, 'Head of Section created successfully.')
        else:
            messages.success(self.request, 'User created successfully.')
            
        return response

class UserUpdateView(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView):
    model = User
    form_class = UserForm
    template_name = 'users/user_form.html'
    
    def test_func(self):
        return self.request.user.is_staff
    
    def get_success_url(self):
        return reverse_lazy('users:user_detail', kwargs={'pk': self.object.pk})
    
    def form_valid(self, form):
        messages.success(self.request, 'User updated successfully.')
        return super().form_valid(form)

class UserDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):
    model = User
    template_name = 'users/user_confirm_delete.html'
    success_url = reverse_lazy('users:user_list')
    
    def test_func(self):
        return self.request.user.is_superuser
    
    def delete(self, request, *args, **kwargs):
        messages.success(request, 'User deleted successfully.')
        return super().delete(request, *args, **kwargs)
