from datetime import timedelta
from django.conf import settings
from django.db import OperationalError, ProgrammingError
from django.urls import reverse
from django.utils import timezone

from .services import get_profile, two_factor_enabled


def k4w_shell(request):
    context = {
        "k4w_version": getattr(settings, "K4W_VERSION", "8.0.0"),
        "k4w_environment": getattr(settings, "K4W_ENVIRONMENT", "Desenvolvimento"),
        "k4w_demo_mode": getattr(settings, "DEMO_MODE", False),
        "k4w_admin_notifications": [],
        "k4w_client_notifications": [],
        "k4w_notification_count": 0,
    }
    user = getattr(request, "user", None)
    if not user or not user.is_authenticated:
        return context
    try:
        context["k4w_user_profile"] = get_profile(user)
        context["k4w_two_factor_enabled"] = two_factor_enabled(user)
        if user.is_staff:
            from billing.models import Payment
            from notifications.models import NotificationLog
            from operations.models import InternalTask
            from support.models import SupportMessage
            from monitoring.models import MonitorIncident

            unread_support = SupportMessage.objects.filter(
                author_type=SupportMessage.AuthorType.CLIENT,
                read_by_staff_at__isnull=True,
            ).count()
            failed_emails = NotificationLog.objects.filter(status=NotificationLog.Status.FAILED).count()
            overdue_tasks = InternalTask.objects.filter(
                due_date__lt=timezone.localdate(),
            ).exclude(status__in=[InternalTask.Status.DONE, InternalTask.Status.CANCELLED]).count()
            payment_review = Payment.objects.filter(status=Payment.Status.VALIDATING).count()
            monitoring_incidents = MonitorIncident.objects.filter(
                status__in=[MonitorIncident.Status.OPEN, MonitorIncident.Status.ACKNOWLEDGED]
            ).count()
            items = [
                {
                    "title": "Mensagens de clientes",
                    "count": unread_support,
                    "icon": "forum",
                    "url": reverse("admin:support_supportmessage_changelist"),
                    "tone": "danger" if unread_support else "neutral",
                },
                {
                    "title": "Pagamentos por validar",
                    "count": payment_review,
                    "icon": "payments",
                    "url": reverse("admin:billing_payment_changelist") + "?status=validating",
                    "tone": "warning" if payment_review else "neutral",
                },
                {
                    "title": "Tarefas em atraso",
                    "count": overdue_tasks,
                    "icon": "event_busy",
                    "url": reverse("operations_center"),
                    "tone": "danger" if overdue_tasks else "neutral",
                },
                {
                    "title": "Incidentes de websites",
                    "count": monitoring_incidents,
                    "icon": "crisis_alert",
                    "url": reverse("monitoring_center"),
                    "tone": "danger" if monitoring_incidents else "neutral",
                },
                {
                    "title": "Emails com falha",
                    "count": failed_emails,
                    "icon": "mark_email_unread",
                    "url": reverse("admin:notifications_notificationlog_changelist") + "?status=failed",
                    "tone": "warning" if failed_emails else "neutral",
                },
            ]
            context["k4w_admin_notifications"] = items
            context["k4w_notification_count"] = sum(item["count"] for item in items)
        else:
            try:
                access = user.client_portal_access
            except Exception:
                access = None
            if access and access.is_active:
                from billing.models import Payment, Renewal
                from support.models import SupportMessage
                from monitoring.models import MonitorIncident

                client = access.client
                today = timezone.localdate()
                unread = SupportMessage.objects.filter(
                    ticket__client=client,
                    ticket__client_visible=True,
                    author_type=SupportMessage.AuthorType.STAFF,
                    is_internal=False,
                    read_by_client_at__isnull=True,
                ).count()
                renewals = Renewal.objects.filter(
                    service__client=client,
                    due_date__range=(today, today + timedelta(days=30)),
                ).exclude(status=Renewal.Status.CANCELLED).count()
                incidents = MonitorIncident.objects.filter(
                    monitor__technical_asset__service__client=client,
                    client_visible=True,
                    status__in=[MonitorIncident.Status.OPEN, MonitorIncident.Status.ACKNOWLEDGED],
                ).count()
                payments = 0
                if access.can_view_financial:
                    payments = Payment.objects.filter(
                        renewal__service__client=client,
                    ).exclude(status__in=[Payment.Status.PAID, Payment.Status.CANCELLED, Payment.Status.REFUNDED]).count()
                items = [
                    {"title": "Novas respostas de suporte", "count": unread, "url": reverse("client_portal:tickets"), "icon": "forum"},
                    {"title": "Renovações nos próximos 30 dias", "count": renewals, "url": reverse("client_portal:renewals"), "icon": "event_repeat"},
                    {"title": "Incidentes dos websites", "count": incidents, "url": reverse("client_portal:monitoring"), "icon": "monitor_heart"},
                ]
                if access.can_view_financial:
                    items.append({"title": "Pagamentos pendentes", "count": payments, "url": reverse("client_portal:payments"), "icon": "payments"})
                context["k4w_client_notifications"] = items
                context["k4w_notification_count"] = sum(item["count"] for item in items)
    except (OperationalError, ProgrammingError):
        pass
    return context
