"""Alumni dashboard widgets — alumni members & alumni officers."""
from __future__ import annotations

import json

from django.urls import reverse
from django.utils import timezone

from apps.core.dashboard.base import (
    ZONE_ACTIONS,
    ZONE_KPI,
    ZONE_PRIMARY,
    ZONE_SIDE,
    DashboardWidget,
)
from apps.core.dashboard.registry import register
from apps.core.dashboard.role_groups import (
    ALUMNI_OFFICER_ROLES,
    ALUMNI_ROLES,
    has_role,
)


def _alumni_profile(user):
    try:
        from apps.alumni.profiles.models import AlumniProfile
        return AlumniProfile.objects.filter(user=user).first()
    except Exception:  # noqa: BLE001
        return None


# ── Alumni: my profile banner ────────────────────────────────────────────


@register
class MyAlumniProfileBanner(DashboardWidget):
    key = "alumni.profile_banner"
    zone = ZONE_PRIMARY
    priority = 5
    template = "core/dashboard/widgets/banner_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES)

    def get_context(self, user) -> dict:
        profile = _alumni_profile(user)
        if profile is None:
            return {
                "title": "Set up your alumni profile",
                "body": "Add your current role and ORCID iD to appear in the alumni directory.",
                "cta_label": "Edit profile",
                "cta_href": reverse("alumni_profiles:profile_edit_self"),
                "accent": "amber",
            }
        return {
            "title": f"{profile.current_position or 'Alumni'} {('@ ' + profile.current_employer) if profile.current_employer else ''}",
            "body": "Stay connected — log milestones and explore the network.",
            "cta_label": "Edit profile",
            "cta_href": reverse("alumni_profiles:profile_edit_self"),
        }


# ── Alumni KPIs ──────────────────────────────────────────────────────────


class _AlumniKPIBase(DashboardWidget):
    zone = ZONE_KPI
    template = "core/dashboard/widgets/kpi_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES)


@register
class AlumniMilestonesKPI(_AlumniKPIBase):
    key = "alumni.kpi.milestones"
    priority = 110

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.tracking.models import CareerMilestone
            n = CareerMilestone.objects.filter(profile__user=user).count()
        except Exception:  # noqa: BLE001
            n = 0
        return {"label": "Career milestones", "value": f"{n:,}", "hint": "Tracked over time"}


@register
class AlumniPublicationsKPI(_AlumniKPIBase):
    key = "alumni.kpi.publications"
    priority = 111

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.profiles.models import Publication
            n = Publication.objects.filter(profile__user=user).count()
        except Exception:  # noqa: BLE001
            n = 0
        return {"label": "Publications", "value": f"{n:,}", "hint": "On your profile"}


@register
class AlumniMentorshipsKPI(_AlumniKPIBase):
    key = "alumni.kpi.mentorships"
    priority = 112

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.engagement.models import MentorshipPairing, MentorshipStatus
            as_mentor = MentorshipPairing.objects.filter(mentor__user=user, status=MentorshipStatus.ACTIVE).count()
            as_mentee = MentorshipPairing.objects.filter(mentee=user, status=MentorshipStatus.ACTIVE).count()
            total = as_mentor + as_mentee
        except Exception:  # noqa: BLE001
            total = 0
            as_mentor = as_mentee = 0
        return {
            "label": "Active mentorships",
            "value": f"{total:,}",
            "hint": f"{as_mentor} mentoring · {as_mentee} as mentee",
            "href": reverse("alumni_engagement:mentorship_list"),
        }


@register
class AlumniNetworkGroupsKPI(_AlumniKPIBase):
    key = "alumni.kpi.network_groups"
    priority = 113

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.engagement.models import GroupMembership
            n = GroupMembership.objects.filter(user=user).count()
        except Exception:  # noqa: BLE001
            n = 0
        return {
            "label": "Network groups",
            "value": f"{n:,}",
            "accent": "emerald" if n else "primary",
            "hint": "Communities you've joined" if n else "Discover your network",
            "href": reverse("alumni_engagement:network_group_list"),
        }


# ── Alumni: upcoming events list ─────────────────────────────────────────


@register
class UpcomingAlumniEventsWidget(DashboardWidget):
    key = "alumni.events"
    zone = ZONE_SIDE
    priority = 100
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES) or has_role(user, ALUMNI_OFFICER_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.engagement.models import AlumniEvent
            now = timezone.now()
            qs = AlumniEvent.objects.filter(start_at__gte=now).order_by("start_at")[:5]
            for e in qs:
                items.append({
                    "label": e.title,
                    "sublabel": e.start_at.strftime("%b %d, %Y · %H:%M"),
                    "badge": "Upcoming",
                    "badge_color": "sky",
                    "href": reverse("alumni_engagement:event_detail", kwargs={"slug": e.slug}),
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Upcoming events",
            "items": items,
            "empty_text": "No upcoming events scheduled.",
            "footer_href": reverse("alumni_engagement:event_list"),
            "footer_label": "Browse events",
        }


# ── Alumni: my mentorships list ──────────────────────────────────────────


@register
class MyMentorshipsWidget(DashboardWidget):
    key = "alumni.my_mentorships"
    zone = ZONE_PRIMARY
    priority = 110
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.engagement.models import MentorshipPairing, MentorshipStatus
            qs = (
                MentorshipPairing.objects.filter(mentor__user=user, status__in=[MentorshipStatus.REQUESTED, MentorshipStatus.ACTIVE])
                .select_related("mentee")[:5]
            )
            for p in qs:
                mentee = p.mentee.get_full_name() or p.mentee.email
                color = "amber" if p.status == MentorshipStatus.REQUESTED else "emerald"
                items.append({
                    "label": mentee,
                    "sublabel": p.topic or "Mentorship pairing",
                    "badge": p.get_status_display(),
                    "badge_color": color,
                    "href": reverse("alumni_engagement:mentorship_list"),
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Mentorships",
            "items": items,
            "empty_text": "No active mentorships.",
            "footer_href": reverse("alumni_engagement:mentorship_list"),
            "footer_label": "View all",
        }


# ── Alumni: Recent group announcements ───────────────────────────────────


@register
class AlumniRecentGroupActivityWidget(DashboardWidget):
    key = "alumni.recent_group_activity"
    zone = ZONE_PRIMARY
    priority = 115
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.engagement.models import GroupAnnouncement, GroupMembership
            my_group_ids = list(
                GroupMembership.objects.filter(user=user).values_list("group_id", flat=True)
            )
            if my_group_ids:
                qs = (
                    GroupAnnouncement.objects.filter(group_id__in=my_group_ids)
                    .select_related("group", "author")
                    .order_by("-created_at")[:5]
                )
                for a in qs:
                    items.append({
                        "label": a.title,
                        "sublabel": f"{a.group.slug} · {timezone.localtime(a.created_at).strftime('%b %d')}",
                        "badge": "Update",
                        "badge_color": "sky",
                    })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Group activity",
            "subtitle": "Announcements from your network groups",
            "items": items,
            "empty_text": "Join a network group to see updates here.",
            "footer_href": reverse("alumni_engagement:network_group_list"),
            "footer_label": "Browse groups",
        }


# ── Alumni quick actions ─────────────────────────────────────────────────


@register
class AlumniQuickActions(DashboardWidget):
    key = "alumni.actions"
    zone = ZONE_ACTIONS
    priority = 80
    template = "core/dashboard/widgets/quick_actions.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES)

    def get_context(self, user) -> dict:
        return {
            "actions": [
                {
                    "label": "Edit profile",
                    "href": reverse("alumni_profiles:profile_edit_self"),
                    "primary": True,
                    "icon": "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",
                },
                {
                    "label": "Browse directory",
                    "href": reverse("alumni_profiles:directory"),
                    "icon": "M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z",
                },
                {
                    "label": "Events",
                    "href": reverse("alumni_engagement:event_list"),
                    "icon": "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z",
                },
            ],
        }


# ── Alumni officer KPIs ──────────────────────────────────────────────────


class _AlumniOfficerKPIBase(DashboardWidget):
    zone = ZONE_KPI
    template = "core/dashboard/widgets/kpi_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_OFFICER_ROLES)


@register
class AlumniTotalProfilesKPI(_AlumniOfficerKPIBase):
    key = "alumni.kpi.total_profiles"
    priority = 120

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.profiles.models import AlumniProfile
            n = AlumniProfile.objects.count()
        except Exception:  # noqa: BLE001
            n = 0
        return {
            "label": "Alumni profiles",
            "value": f"{n:,}",
            "hint": "Total in directory",
            "href": reverse("alumni_profiles:admin_list"),
        }


@register
class AlumniUpcomingEventsKPI(_AlumniOfficerKPIBase):
    key = "alumni.kpi.upcoming_events"
    priority = 121

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.engagement.models import AlumniEvent
            n = AlumniEvent.objects.filter(start_at__gte=timezone.now()).count()
        except Exception:  # noqa: BLE001
            n = 0
        return {
            "label": "Upcoming events",
            "value": f"{n:,}",
            "hint": "Scheduled in the future",
            "href": reverse("alumni_engagement:event_list"),
        }


@register
class AlumniPendingMentorshipsKPI(_AlumniOfficerKPIBase):
    key = "alumni.kpi.pending_mentorships"
    priority = 122

    def get_context(self, user) -> dict:
        try:
            from apps.alumni.engagement.models import MentorshipPairing, MentorshipStatus
            n = MentorshipPairing.objects.filter(status=MentorshipStatus.REQUESTED).count()
        except Exception:  # noqa: BLE001
            n = 0
        return {
            "label": "Mentorship requests",
            "value": f"{n:,}",
            "accent": "amber" if n else "primary",
            "hint": "Pending pairings",
        }


# ── Alumni officer: Recent registrations + pending mentorship requests ───


@register
class AlumniOfficerRecentRegistrationsWidget(DashboardWidget):
    key = "alumni.officer_recent_registrations"
    zone = ZONE_PRIMARY
    priority = 120
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_OFFICER_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.profiles.models import AlumniProfile
            qs = (
                AlumniProfile.objects.select_related("user", "current_institution")
                .order_by("-pk")[:6]
            )
            for p in qs:
                badge = "Visible" if getattr(p, "visibility_consent", False) else "Hidden"
                color = "emerald" if getattr(p, "visibility_consent", False) else "neutral"
                items.append({
                    "label": p.user.get_full_name() or p.user.email,
                    "sublabel": f"{p.current_position or ''} {('@ ' + p.current_employer) if p.current_employer else ''}".strip(),
                    "badge": badge,
                    "badge_color": color,
                    "href": reverse("alumni_profiles:profile_detail", kwargs={"pk": p.pk}),
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Recent alumni profiles",
            "subtitle": "Latest registrations",
            "items": items,
            "empty_text": "No alumni profiles yet.",
            "footer_href": reverse("alumni_profiles:admin_list"),
            "footer_label": "Manage profiles",
        }


@register
class AlumniOfficerMentorshipRequestsWidget(DashboardWidget):
    key = "alumni.officer_mentorship_requests"
    zone = ZONE_SIDE
    priority = 90
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_OFFICER_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.engagement.models import MentorshipPairing, MentorshipStatus
            qs = (
                MentorshipPairing.objects.filter(status=MentorshipStatus.REQUESTED)
                .select_related("mentor__user", "mentee")
                .order_by("-created_at")[:5]
            )
            for p in qs:
                mentor = p.mentor.user.get_full_name() or p.mentor.user.email
                mentee = p.mentee.get_full_name() or p.mentee.email
                items.append({
                    "label": f"{mentee} → {mentor}",
                    "sublabel": p.topic or "Pairing requested",
                    "badge": "Requested",
                    "badge_color": "amber",
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Mentorship requests",
            "subtitle": "Awaiting decision",
            "items": items,
            "empty_text": "No pending requests.",
        }


@register
class AlumniOfficerActions(DashboardWidget):
    key = "alumni.officer_actions"
    zone = ZONE_ACTIONS
    priority = 85
    template = "core/dashboard/widgets/quick_actions.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_OFFICER_ROLES)

    def get_context(self, user) -> dict:
        return {
            "actions": [
                {"label": "Schedule event", "href": reverse("alumni_engagement:event_create"), "primary": True, "icon": "M12 4v16m8-8H4"},
                {
                    "label": "Pending events",
                    "href": reverse("alumni_engagement:event_approval_queue"),
                    "icon": "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z",
                },
                {
                    "label": "Pending job listings",
                    "href": reverse("alumni_jobs:pending"),
                    "icon": "M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z",
                },
                {
                    "label": "Chapter leadership requests",
                    "href": reverse("alumni_engagement:leadership_request_queue"),
                    "icon": "M11.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z",
                },
                {
                    "label": "Launch impact survey",
                    "href": reverse("alumni_tracking:impact_survey_launch"),
                    "icon": "M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z",
                },
                {
                    "label": "Profiles directory",
                    "href": reverse("alumni_profiles:admin_list"),
                    "icon": "M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z",
                },
                {
                    "label": "Recognition cockpit",
                    "href": reverse("alumni_recognition:cockpit"),
                    "icon": "M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z",
                },
            ],
        }


# ── Alumni: featured spotlights (recognition) ────────────────────────────


@register
class AlumniActiveSpotlightsWidget(DashboardWidget):
    key = "alumni.active_spotlights"
    zone = ZONE_SIDE
    priority = 105
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.recognition.models import Spotlight
            today = timezone.now().date()
            qs = (
                Spotlight.objects.filter(
                    is_active=True,
                    featured_from__lte=today,
                    featured_until__gte=today,
                )
                .select_related("profile", "profile__user")
                .order_by("-featured_from")[:5]
            )
            for sp in qs:
                profile = sp.profile
                name = (
                    profile.user.get_full_name() or profile.user.email
                ) if profile and profile.user_id else sp.title
                items.append({
                    "label": sp.title,
                    "sublabel": f"{sp.get_category_display()} · {name}",
                    "badge": sp.period_label,
                    "badge_color": "emerald",
                    "href": reverse("alumni_recognition:spotlight_detail", args=[sp.pk]),
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Featured spotlights",
            "subtitle": "Active recognition",
            "items": items,
            "empty_text": "No active spotlights right now.",
            "footer_href": reverse("alumni_recognition:spotlight_list"),
            "footer_label": "All spotlights",
        }


# ── Officer: scheduled broadcasts + active spotlights ───────────────────


@register
class OfficerScheduledBroadcastsWidget(DashboardWidget):
    key = "alumni.officer_scheduled_broadcasts"
    zone = ZONE_PRIMARY
    priority = 130
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_OFFICER_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.recognition.models import Broadcast
            qs = (
                Broadcast.objects.filter(status__in=["draft", "scheduled"])
                .order_by("scheduled_for", "-id")[:5]
            )
            color_map = {
                "draft": "neutral",
                "scheduled": "sky",
                "sending": "amber",
                "sent": "emerald",
                "failed": "rose",
            }
            for b in qs:
                when = (
                    timezone.localtime(b.scheduled_for).strftime("%b %d, %H:%M")
                    if b.scheduled_for else "Not scheduled"
                )
                items.append({
                    "label": getattr(b, "subject", None) or getattr(b, "title", "Broadcast"),
                    "sublabel": when,
                    "badge": b.get_status_display(),
                    "badge_color": color_map.get(b.status, "neutral"),
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Upcoming broadcasts",
            "subtitle": "Scheduled or in draft",
            "items": items,
            "empty_text": "No upcoming broadcasts.",
            "footer_href": reverse("alumni_recognition:broadcast_list"),
            "footer_label": "Manage broadcasts",
        }


@register
class OfficerActiveSpotlightsWidget(DashboardWidget):
    key = "alumni.officer_active_spotlights"
    zone = ZONE_PRIMARY
    priority = 135
    template = "core/dashboard/widgets/list_card.html"

    @classmethod
    def is_enabled(cls, user) -> bool:
        return has_role(user, ALUMNI_OFFICER_ROLES)

    def get_context(self, user) -> dict:
        items: list = []
        try:
            from apps.alumni.recognition.models import Spotlight
            today = timezone.now().date()
            qs = (
                Spotlight.objects.filter(
                    is_active=True,
                    featured_from__lte=today,
                    featured_until__gte=today,
                )
                .select_related("profile__user")
                .order_by("-featured_from")[:5]
            )
            for sp in qs:
                ends = sp.featured_until.strftime("%b %d") if sp.featured_until else ""
                items.append({
                    "label": sp.title,
                    "sublabel": f"{sp.get_category_display()} · ends {ends}",
                    "badge": sp.period_label,
                    "badge_color": "emerald",
                    "href": reverse("alumni_recognition:spotlight_detail", args=[sp.pk]),
                })
        except Exception:  # noqa: BLE001
            pass
        return {
            "title": "Active spotlights",
            "subtitle": "Currently featured",
            "items": items,
            "empty_text": "No active spotlights this period.",
            "footer_href": reverse("alumni_recognition:cockpit"),
            "footer_label": "Open cockpit",
        }
