import json
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from datetime import timedelta
from exams.models import Student
from exams.models_delegation import TaskDelegation
from .constants import STANDARD_CLASSES
from exams.navigation import TEACHER_MENU, STUDENT_MENU

@login_required
def owner_delegations(request):
    if not request.user.is_superuser:
        messages.error(request, "Access Denied. Only the Owner can access this page.")
        return redirect('portal-dashboard')

    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'revoke':
            delegation_id = request.POST.get('delegation_id')
            try:
                TaskDelegation.objects.filter(id=delegation_id).delete()
                messages.success(request, "Delegation revoked successfully.")
            except Exception as e:
                messages.error(request, f"Error revoking delegation: {e}")
            return redirect('owner_delegations')

        assignee_id = request.POST.get('assignee')
        target_url = request.POST.get('target_url', '').strip()
        target_class = request.POST.get('target_class', 'ALL')
        hours_str = request.POST.get('hours', '24')
        notes = request.POST.get('notes', '').strip()

        try:
            hours = float(hours_str)
            if hours <= 0.01 or hours > 8760:  # 8760 hours = 365 days
                hours = 24
        except ValueError:
            hours = 24

        expires_at = timezone.now() + timedelta(hours=hours)

        try:
            assignee = get_user_model().objects.get(id=assignee_id)
            TaskDelegation.objects.create(
                assignee=assignee, 
                task_type='CUSTOM_PAGE', 
                target_class=target_class, 
                custom_url=target_url,
                expires_at=expires_at, 
                created_by=request.user
            )
            messages.success(request, f"Access granted to {assignee.username} for {hours} hours.")
        except Exception as e:
            messages.error(request, f"Error creating delegation: {e}")
        return redirect('owner_delegations')

    # Build the Master Page List from the Central Registry
    delegatable_pages = []
    for group_name, items in (TEACHER_MENU + STUDENT_MENU):
        group_items = []
        for label, url, desc in items:
            # Skip delegating the access control page itself to prevent recursion
            if 'delegations' in url or 'access-control' in label.lower():
                continue
            # Resolve the URL to its path
            final_url = url if url.startswith('/') else '/' + url # Fallback for names if not resolved
            # For simplicity in this dropdown, we just use the raw string provided in the registry
            # If it's a name, the student might not have the named URL, so we just use the path if provided.
            group_items.append({'label': label, 'url': url, 'desc': desc})
        if group_items:
            delegatable_pages.append((group_name, group_items))

    student_user_ids = Student.objects.filter(is_active=True, student_user__isnull=False).values_list('student_user_id', flat=True)
    users = get_user_model().objects.filter(id__in=student_user_ids).order_by('first_name', 'username')
    
    active_delegations = TaskDelegation.objects.filter(
        expires_at__gt=timezone.now()
    ).order_by('-created_at')

    ctx = {
        'users': users,
        'delegations': active_delegations,
        'classes': STANDARD_CLASSES,
        'delegatable_pages': delegatable_pages,
        'default_url': request.GET.get('custom_url', ''),
    }
    return render(request, 'exams/owner_delegations.html', ctx)
