"""
Context processors for global template variables
"""

from django.db.models import Q


def sidebar_counts(request):
    """
    Provide counts for sidebar badges.

    Returns counts for:
    - Active complaints
    - Pending feedback
    - Open PX actions
    - Provisional users (PX Admin only)
    """
    if not request.user.is_authenticated:
        return {}

    from apps.complaints.models import Complaint
    from apps.feedback.models import Feedback
    from apps.px_action_center.models import PXAction

    user = request.user

    # Source Users only see their own created complaints
    if user.is_source_user():
        complaint_count = Complaint.objects.filter(created_by=user, status__in=["open", "in_progress"]).count()
        return {
            "complaint_count": complaint_count,
            "feedback_count": 0,
            "action_count": 0,
            "current_hospital": None,
            "is_px_admin": False,
            "is_source_user": True,
        }

    # Filter based on user role and tenant_hospital
    if user.is_px_admin():
        # PX Admins use their selected hospital from session
        hospital = getattr(request, "tenant_hospital", None)
        if hospital:
            complaint_count = Complaint.objects.filter(hospital=hospital, status__in=["open", "in_progress"]).count()
            feedback_count = Feedback.objects.filter(hospital=hospital, status__in=["submitted", "reviewed"]).count()
            action_count = PXAction.objects.filter(hospital=hospital, status__in=["open", "in_progress"]).count()
        else:
            complaint_count = 0
            feedback_count = 0
            action_count = 0
        # Count provisional users for PX Admin
        from apps.accounts.models import User

        provisional_user_count = User.objects.filter(is_provisional=True, acknowledgement_completed=False).count()
    elif user.hospital:
        complaint_count = Complaint.objects.filter(hospital=user.hospital, status__in=["open", "in_progress"]).count()
        feedback_count = Feedback.objects.filter(hospital=user.hospital, status__in=["submitted", "reviewed"]).count()
        action_count = PXAction.objects.filter(hospital=user.hospital, status__in=["open", "in_progress"]).count()
        # provisional_user_count = 0
    else:
        complaint_count = 0
        feedback_count = 0
        action_count = 0

    # Get unread notification count
    notification_count = 0
    if request.user.is_authenticated:
        from apps.notifications.models import UserNotification

        notification_count = UserNotification.objects.filter(
            user=request.user, is_read=False, is_dismissed=False
        ).count()

    # Draft appreciation count for reviewers
    draft_appreciation_count = 0
    if user.is_px_admin() or user.is_hospital_admin() or user.is_px_management():
        from apps.appreciation.models import Appreciation, AppreciationStatus

        qs = Appreciation.objects.filter(status=AppreciationStatus.DRAFT)
        hospital = getattr(request, "tenant_hospital", None) or user.hospital
        if hospital and not user.is_px_admin():
            qs = qs.filter(hospital=hospital)
        draft_appreciation_count = qs.count()

    return {
        "complaint_count": complaint_count,
        "feedback_count": feedback_count,
        "action_count": action_count,
        "notification_count": notification_count,
        "draft_appreciation_count": draft_appreciation_count,
        "current_hospital": getattr(request, "tenant_hospital", None),
        "is_px_admin": request.user.is_authenticated and request.user.is_px_admin(),
        "is_source_user": False,
    }


def hospital_context(request):
    """
    Provide current hospital context to templates.

    This ensures hospital information is available in the header for all pages.
    """
    if not request.user.is_authenticated:
        return {}

    hospital = getattr(request, "tenant_hospital", None)

    # Get list of hospitals for PX Admin switcher
    hospitals_list = []
    if request.user.is_px_admin():
        from apps.organizations.models import Hospital

        hospitals_list = list(
            Hospital.objects.filter(status="active")
            .order_by("name")
            .values("id", "name", "display_name", "display_name_ar", "code")
        )

    # Source user context
    is_source_user = request.user.is_source_user()
    source_user_profile = getattr(request, "source_user_profile", None)

    return {
        "current_hospital": hospital,
        "is_px_admin": request.user.is_px_admin(),
        "is_source_user": is_source_user,
        "source_user_profile": source_user_profile,
        "hospitals_list": hospitals_list,
        "show_hospital_selector": False,
    }
