"""
QI Projects Console UI views
"""
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import get_object_or_404, render

from apps.organizations.models import Hospital

from .models import QIProject


@login_required
def project_list(request):
    """QI Projects list view"""
    queryset = QIProject.objects.select_related(
        'hospital', 'department', 'project_lead'
    ).prefetch_related('team_members', 'related_actions')
    
    # Apply RBAC filters
    user = request.user
    if not user.is_px_admin() and user.hospital:
        queryset = queryset.filter(hospital=user.hospital)
    
    # Apply filters
    status_filter = request.GET.get('status')
    if status_filter:
        queryset = queryset.filter(status=status_filter)
    
    hospital_filter = request.GET.get('hospital')
    if hospital_filter:
        queryset = queryset.filter(hospital_id=hospital_filter)
    
    # Search
    search_query = request.GET.get('search')
    if search_query:
        queryset = queryset.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query)
        )
    
    # Ordering
    queryset = queryset.order_by('-created_at')
    
    # Pagination
    page_size = int(request.GET.get('page_size', 25))
    paginator = Paginator(queryset, page_size)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    # Get hospitals for filter
    hospitals = Hospital.objects.filter(status='active')
    if not user.is_px_admin() and user.hospital:
        hospitals = hospitals.filter(id=user.hospital.id)
    
    # Statistics
    stats = {
        'total': queryset.count(),
        'active': queryset.filter(status='active').count(),
        'completed': queryset.filter(status='completed').count(),
    }
    
    context = {
        'page_obj': page_obj,
        'projects': page_obj.object_list,
        'hospitals': hospitals,
        'stats': stats,
        'filters': request.GET,
    }
    
    return render(request, 'projects/project_list.html', context)


@login_required
def project_detail(request, pk):
    """QI Project detail view"""
    project = get_object_or_404(
        QIProject.objects.select_related(
            'hospital', 'department', 'project_lead'
        ).prefetch_related(
            'team_members', 'related_actions', 'tasks'
        ),
        pk=pk
    )
    
    # Get tasks
    tasks = project.tasks.all().order_by('order')
    
    context = {
        'project': project,
        'tasks': tasks,
    }
    
    return render(request, 'projects/project_detail.html', context)
