from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import CreateView, ListView, DetailView
from django.urls import reverse_lazy
from django.utils import timezone
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods

from tasks.models import Task
from .models import Report
from .forms import ReportSubmissionForm

@login_required
@permission_required('reports.can_submit_report', raise_exception=True)
@require_http_methods(["GET", "POST"])
def submit_report(request):
    """Handle report submission."""
    if request.method == 'POST':
        form = ReportSubmissionForm(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            report = form.save(commit=False)
            report.created_by = request.user
            report.status = 'submitted'
            report.save()
            
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({
                    'success': True,
                    'message': 'Report submitted successfully!',
                    'report_id': report.id
                })
            messages.success(request, 'Report submitted successfully!')
            return redirect('reports:view_report', pk=report.id)
        
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'success': False,
                'errors': form.errors
            }, status=400)
    else:
        form = ReportSubmissionForm(user=request.user)
    
    return render(request, 'reports/submit_report.html', {'form': form})

@login_required
def view_report(request, pk):
    """View a specific report."""
    report = get_object_or_404(Report, pk=pk)
    return render(request, 'reports/report_detail.html', {'report': report})

@login_required
def report_list(request):
    """List all reports for the current user."""
    reports = Report.objects.filter(created_by=request.user).order_by('-created_at')
    return render(request, 'reports/report_list.html', {'reports': reports})

@login_required
def generate_report(request):
    """Generate a simple report of tasks."""
    tasks = Task.objects.all()[:10]  # Just get the first 10 tasks for demo
    context = {'tasks': tasks}
    return render(request, 'reports/generate.html', context)

@login_required
def department_performance(request, department_id):
    """Generate a performance report for a specific department."""
    from django.shortcuts import get_object_or_404
    from users.models import Department
    from tasks.models import Task
    
    department = get_object_or_404(Department, id=department_id)
    
    # Get all tasks for this department
    tasks = Task.objects.filter(assigned_to__department=department)
    
    # Calculate some basic statistics
    total_tasks = tasks.count()
    completed_tasks = tasks.filter(status='completed').count()
    in_progress_tasks = tasks.filter(status='in_progress').count()
    pending_tasks = tasks.filter(status='pending').count()
    
    # Calculate priority-based statistics
    high_priority_tasks = tasks.filter(priority='high').count()
    medium_priority_tasks = tasks.filter(priority='medium').count()
    low_priority_tasks = tasks.filter(priority='low').count()
    
    context = {
        'department': department,
        'total_tasks': total_tasks,
        'completed_tasks': completed_tasks,
        'in_progress_tasks': in_progress_tasks,
        'pending_tasks': pending_tasks,
        'high_priority_tasks': high_priority_tasks,
        'medium_priority_tasks': medium_priority_tasks,
        'low_priority_tasks': low_priority_tasks,
        'completion_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0,
    }
    
    return render(request, 'reports/department_performance.html', context)
