from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import TemplateView
from django.db.models import Count, Q, F, Case, When, Value, IntegerField
from django.utils import timezone
from datetime import timedelta

from ..tasks.models import Task
from .models import User, Department, UserRole

class DirectorDashboardView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
    template_name = 'dashboards/director_dashboard.html'
    
    def test_func(self):
        # Only Director General can access this view
        return hasattr(self.request.user, 'role') and self.request.user.role.name == 'director'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = self.request.user
        department = user.department
        
        if not department:
            return context
            
        # Get all sections under this department
        sections = Department.objects.filter(parent=department)
        
        # Get all users in this department and its sections
        department_users = User.objects.filter(
            Q(department=department) | Q(department__in=sections)
        )
        
        # Get all tasks in this department and its sections
        department_tasks = Task.objects.filter(
            Q(assigned_to__department=department) |
            Q(assigned_to__department__in=sections)
        )
        
        # Get Heads of Sections
        head_role = UserRole.objects.get(name='head')
        heads_of_sections = User.objects.filter(
            role=head_role,
            department__in=sections
        ).select_related('department')
        
        # Task statistics
        total_tasks = department_tasks.count()
        pending_tasks = department_tasks.filter(status='pending').count()
        in_progress_tasks = department_tasks.filter(status='in_progress').count()
        completed_tasks = department_tasks.filter(status='completed').count()
        
        # Calculate completion rate (avoid division by zero)
        completion_rate = 0
        if total_tasks > 0:
            completion_rate = round((completed_tasks / total_tasks) * 100)
        
        # Get recent tasks (last 10)
        recent_tasks = department_tasks.order_by('-created_at')[:10]
        
        # Get task status distribution for charts
        task_status_data = {
            'labels': ['Pending', 'In Progress', 'Completed'],
            'data': [pending_tasks, in_progress_tasks, completed_tasks],
            'colors': ['#f6c23e', '#4e73df', '#1cc88a']
        }
        
        # Get tasks by section for charts
        tasks_by_section = department_tasks.values(
            'assigned_to__department__name'
        ).annotate(
            total=Count('id'),
            completed=Count('id', filter=Q(status='completed')),
            in_progress=Count('id', filter=Q(status='in_progress')),
            pending=Count('id', filter=Q(status='pending')),
        ).order_by('-total')
        
        context.update({
            'department': department,
            'sections': sections,
            'total_users': department_users.count(),
            'total_tasks': total_tasks,
            'pending_tasks': pending_tasks,
            'in_progress_tasks': in_progress_tasks,
            'completed_tasks': completed_tasks,
            'completion_rate': completion_rate,
            'recent_tasks': recent_tasks,
            'department_tasks': department_tasks,
            'heads_of_sections': heads_of_sections,
            'task_status_data': task_status_data,
            'tasks_by_section': list(tasks_by_section),
        })
        
        return context
