import logging
from datetime import timedelta
from django.shortcuts import render, redirect
from django.utils import timezone
from django.contrib.auth.decorators import login_required, user_passes_test
from django.db.models import Count, Q, Sum
from django.contrib.auth import get_user_model
from .models import Appointment, Service, StaffMember, AppointmentNote
from tasks.models import Task, TaskComment

logger = logging.getLogger(__name__)

User = get_user_model()

def get_user_stats(user):
    """Get statistics based on user's role and department."""
    stats = {}
    
    # Base query for tasks and appointments
    task_query = Task.objects.all()
    appointment_query = Appointment.objects.all()
    
    # Filter by department if user is not a superuser or president
    if not user.is_superuser and hasattr(user, 'role'):
        if user.role.name == 'minister':
            # Minister can see their department and sub-departments
            task_query = task_query.filter(
                Q(assigned_to__department=user.department) |
                Q(assigned_to__department__parent=user.department)
            )
            appointment_query = appointment_query.filter(
                Q(staff_member__department=user.department) |
                Q(staff_member__department__parent=user.department)
            )
        elif user.role.name in ['director', 'head', 'secretary']:
            # Director/Head/Secretary can only see their own department
            task_query = task_query.filter(assigned_to__department=user.department)
            appointment_query = appointment_query.filter(staff_member__department=user.department)
    
    # Calculate stats
    today = timezone.now().date()
    thirty_days_ago = today - timedelta(days=30)
    
    # Get user counts based on role
    user_stats = User.objects.all()
    if hasattr(user, 'role') and user.role.name != 'president':
        user_stats = user_stats.filter(department=user.department)
    
    stats['total_users'] = user_stats.count()
    
    # Get department count for president and ministers
    if user.is_superuser or (hasattr(user, 'role') and user.role.name in ['president', 'minister']):
        from users.models import Department
        stats['total_departments'] = Department.objects.count()
    
    # Task stats
    stats['total_tasks'] = task_query.count()
    stats['open_tasks'] = task_query.exclude(status='done').count()
    stats['overdue_tasks'] = task_query.filter(
        due_date__lt=today,
        status__in=['todo', 'in_progress']
    ).count()
    stats['completed_tasks_30d'] = task_query.filter(
        status='done',
        completed_at__date__gte=thirty_days_ago
    ).count()
    
    # Appointment stats
    stats['total_appointments'] = appointment_query.count()
    stats['pending_appointments'] = appointment_query.filter(status='pending').count()
    stats['total_revenue'] = appointment_query.filter(
        status='completed',
        start_time__date__gte=thirty_days_ago
    ).aggregate(total=Sum('service__price'))['total'] or 0
    
    return stats

@login_required
@login_required
def admin_dashboard(request):
    if not request.user.is_staff:
        return redirect('home')  # Redirect non-staff users to home
        
    # Debug logging
    logger.debug(f"User: {request.user}")
    logger.debug(f"Is superuser: {request.user.is_superuser}")
    logger.debug(f"Is staff: {request.user.is_staff}")
    logger.debug(f"Has role attr: {hasattr(request.user, 'role')}")
    if hasattr(request.user, 'role'):
        logger.debug(f"User role: {getattr(request.user, 'role', None)}")
    
    # Get user-specific stats based on role
    stats = get_user_stats(request.user)
    stats['total_staff'] = StaffMember.objects.count()
    
    # Get today's date for filtering
    today = timezone.now().date()
    thirty_days_ago = today - timedelta(days=30)
    
    # Get upcoming appointments (next 7 days) with role-based filtering
    upcoming_appointments = Appointment.objects.all()
    
    # Apply role-based filtering
    if not request.user.is_superuser and hasattr(request.user, 'role'):
        if request.user.role.name == 'minister':
            upcoming_appointments = upcoming_appointments.filter(
                Q(staff_member__department=request.user.department) |
                Q(staff_member__department__parent=request.user.department)
            )
        elif request.user.role.name in ['director', 'head', 'secretary']:
            upcoming_appointments = upcoming_appointments.filter(
                staff_member__department=request.user.department
            )
    
    upcoming_appointments = upcoming_appointments.filter(
        start_time__date__gte=today,
        start_time__lte=today + timedelta(days=7)
    ).order_by('start_time')[:5]
    
    # Get recent tasks with role-based filtering
    recent_tasks = Task.objects.select_related('assigned_to', 'created_by')
    
    # Apply role-based filtering
    if not request.user.is_superuser and hasattr(request.user, 'role'):
        if request.user.role.name == 'minister':
            recent_tasks = recent_tasks.filter(
                Q(assigned_to__department=request.user.department) |
                Q(assigned_to__department__parent=request.user.department)
            )
        elif request.user.role.name in ['director', 'head', 'secretary']:
            recent_tasks = recent_tasks.filter(
                assigned_to__department=request.user.department
            )
    
    recent_tasks = recent_tasks.order_by('-created_at')[:5]
    
    # Generate recent activities
    recent_activities = []
    
    # Add recent appointments
    recent_appointments = Appointment.objects.order_by('-created_at')[:3]
    for appt in recent_appointments:
        recent_activities.append({
            'type': 'appointment',
            'title': f"New {appt.get_status_display().lower()} appointment",
            'description': f"{appt.service.name} for {appt.client.get_full_name() or appt.client.username}",
            'timestamp': appt.created_at,
            'link': appt.get_absolute_url()
        })
    
    # Add recent tasks
    recent_tasks_activities = Task.objects.select_related('created_by').order_by('-created_at')[:3]
    for task in recent_tasks_activities:
        recent_activities.append({
            'type': 'task',
            'title': f"New task: {task.title}",
            'description': f"Assigned to {task.assigned_to.get_full_name() or task.assigned_to.username}",
            'timestamp': task.created_at,
            'link': task.get_absolute_url()
        })
    
    # Add recent notes
    recent_notes = AppointmentNote.objects.select_related('appointment').order_by('-created_at')[:3]
    for note in recent_notes:
        recent_activities.append({
            'type': 'note',
            'title': f"New note by {note.author.get_full_name() or note.author.username}",
            'description': f"{note.note[:100]}{'...' if len(note.note) > 100 else ''}",
            'timestamp': note.created_at,
            'link': note.appointment.get_absolute_url()
        })
    
    # Sort activities by timestamp
    recent_activities.sort(key=lambda x: x['timestamp'], reverse=True)
    recent_activities = recent_activities[:5]  # Limit to 5 most recent
    
    # Check user permissions for actions
    if request.user.is_superuser:
        can_manage_users = True
        can_manage_roles = True
        logger.debug("Superuser detected - granting all permissions")
    else:
        can_manage_users = hasattr(request.user, 'role') and request.user.role and \
                         request.user.role.name in ['president', 'minister', 'director']
        can_manage_roles = hasattr(request.user, 'role') and request.user.role and \
                          request.user.role.name == 'president'
        logger.debug(f"Non-superuser permissions - can_manage_users: {can_manage_users}, can_manage_roles: {can_manage_roles}")
    
    # Force permissions for debugging
    logger.debug(f"Before override - can_manage_users: {can_manage_users}, can_manage_roles: {can_manage_roles}")
    can_manage_users = True  # Force True for debugging
    can_manage_roles = True  # Force True for debugging
    logger.debug(f"After override - can_manage_users: {can_manage_users}, can_manage_roles: {can_manage_roles}")
    
    context = {
        'stats': stats,
        'upcoming_appointments': upcoming_appointments,
        'recent_tasks': recent_tasks,
        'recent_activities': recent_activities,
        'can_manage_users': can_manage_users,
        'can_manage_roles': can_manage_roles,
        'user_role': request.user.role.name if hasattr(request.user, 'role') else 'admin',
    }
    
    return render(request, 'admin_dashboard.html', context)
