from __future__ import annotations

from datetime import date
from typing import Any

from fastapi import APIRouter, Request
from fastapi.responses import RedirectResponse
from sqlalchemy import or_, select
from sqlalchemy.orm import Session, selectinload

from app.core.db.common import CommonSessionLocal
from app.core.security.csrf import get_or_create_csrf_token
from app.core.security.session_auth import get_current_user
from app.core.templating import templates
from app.modules.core.rbac.deps import get_user_permissions, get_user_roles
from app.modules.core.rbac.permission_guard import require_permission
from app.modules.employees.service import (
    build_employee_scope,
    list_employee_work_assignable_users,
)
from app.modules.services.execution import CLOSED_TASK_STATUSES, TASK_PRIORITIES, TASK_STATUSES
from app.modules.services.models import ClientServiceSubscription, ClientServiceTaskInstance, ServiceCatalogue, ServiceTaskComment
from app.modules.clients.models import Client

router = APIRouter(prefix="/manager", tags=["manager-workspace-ui"])


def _redirect_login():
    return RedirectResponse(url="/login", status_code=303)


def _redirect_denied():
    from app.core.http_responses import ui_access_denied
    return ui_access_denied()


def _base_ctx(request: Request, db: Session, current_user, **ctx):
    base = {
        "request": request,
        "current_user": current_user,
        "current_user_roles": get_user_roles(db, current_user.id),
        "current_user_permissions": get_user_permissions(db, current_user.id),
        "csrf_token": get_or_create_csrf_token(request),
        "task_statuses": TASK_STATUSES,
        "task_priorities": TASK_PRIORITIES,
    }
    base.update(ctx)
    return base


def _render(request: Request, template_name: str, db: Session, current_user, **ctx):
    return templates.TemplateResponse(template_name, _base_ctx(request, db, current_user, **ctx))


def _task_status_label(task: ClientServiceTaskInstance) -> str:
    return dict(TASK_STATUSES).get(getattr(task, "status", ""), (getattr(task, "status", "") or "-").replace("_", " ").title())


def _task_priority_label(task: ClientServiceTaskInstance) -> str:
    return dict(TASK_PRIORITIES).get(getattr(task, "priority", ""), (getattr(task, "priority", "") or "normal").replace("_", " ").title())




def _active_financial_year(request: Request) -> str | None:
    value = request.session.get("active_financial_year") or getattr(request.state, "year_code", None)
    value = (value or "").strip()
    return value or None

def _subscription_label(subscription: ClientServiceSubscription | None, task: ClientServiceTaskInstance) -> str:
    catalogue = getattr(subscription, "catalogue", None) if subscription else getattr(task, "catalogue", None)
    service_name = getattr(catalogue, "service_name", None) or getattr(catalogue, "name", None) or getattr(task, "task_name", "Engagement")
    fy = getattr(subscription, "financial_year", None) or getattr(task, "financial_year", None)
    return f"{service_name} · FY {fy}" if fy else str(service_name)


def _date_bucket(task: ClientServiceTaskInstance, today: date) -> str:
    target = getattr(task, "internal_target_date", None)
    if not target:
        return "No target date"
    if target < today and (task.status or "") not in CLOSED_TASK_STATUSES:
        return "Overdue"
    if target == today and (task.status or "") not in CLOSED_TASK_STATUSES:
        return "Due today"
    if target > today and (task.status or "") not in CLOSED_TASK_STATUSES:
        return "Upcoming"
    return "Closed"


def _manager_task_query(db: Session, scope, *, q: str = "", assigned_to_user_id: int | None = None, financial_year: str | None = None):
    stmt = (
        select(ClientServiceTaskInstance)
        .options(
            selectinload(ClientServiceTaskInstance.client),
            selectinload(ClientServiceTaskInstance.catalogue),
            selectinload(ClientServiceTaskInstance.subscription).selectinload(ClientServiceSubscription.catalogue),
            selectinload(ClientServiceTaskInstance.subscription).selectinload(ClientServiceSubscription.assigned_partner),
            selectinload(ClientServiceTaskInstance.subscription).selectinload(ClientServiceSubscription.assigned_manager),
            selectinload(ClientServiceTaskInstance.subscription).selectinload(ClientServiceSubscription.assigned_staff),
            selectinload(ClientServiceTaskInstance.assigned_to),
            selectinload(ClientServiceTaskInstance.comments).selectinload(ServiceTaskComment.created_by),
        )
        .where(
            ClientServiceTaskInstance.tenant_id == scope.tenant_id,
            ClientServiceTaskInstance.is_active.is_(True),
        )
    )
    if scope.branch_id is not None:
        stmt = stmt.where(ClientServiceTaskInstance.branch_id == scope.branch_id)
    if financial_year:
        stmt = stmt.where(ClientServiceTaskInstance.financial_year == financial_year.strip())
    if assigned_to_user_id:
        stmt = stmt.where(ClientServiceTaskInstance.assigned_to_user_id == int(assigned_to_user_id))
    if q.strip():
        like = f"%{q.strip()}%"
        stmt = stmt.where(
            or_(
                ClientServiceTaskInstance.task_name.ilike(like),
                ClientServiceTaskInstance.description.ilike(like),
                ClientServiceTaskInstance.client.has(or_(Client.client_name.ilike(like), Client.client_code.ilike(like))),
                ClientServiceTaskInstance.catalogue.has(or_(ServiceCatalogue.service_name.ilike(like), ServiceCatalogue.service_code.ilike(like))),
            )
        )
    return db.execute(
        stmt.order_by(
            ClientServiceTaskInstance.internal_target_date.is_(None),
            ClientServiceTaskInstance.internal_target_date.asc(),
            ClientServiceTaskInstance.priority.desc(),
            ClientServiceTaskInstance.sequence_no.asc(),
            ClientServiceTaskInstance.id.desc(),
        )
    ).scalars().all()


def build_manager_workspace_payload(db: Session, scope, *, q: str = "", assigned_to_user_id: int | None = None, financial_year: str | None = None) -> dict[str, Any]:
    today = date.today()
    tasks = _manager_task_query(db, scope, q=q, assigned_to_user_id=assigned_to_user_id, financial_year=financial_year)

    columns = [
        {"code": "unassigned", "label": "Unassigned", "hint": "Needs manager allocation", "tasks": []},
        {"code": "assigned", "label": "Assigned", "hint": "Assigned but not started", "tasks": []},
        {"code": "in_progress", "label": "In Progress", "hint": "Currently being worked on", "tasks": []},
        {"code": "blocked", "label": "Blocked", "hint": "Needs intervention", "tasks": []},
        {"code": "ready_review", "label": "Completed / Review", "hint": "Completed by staff, review if required", "tasks": []},
    ]
    lookup = {c["code"]: c for c in columns}
    summary = {
        "total": len(tasks),
        "unassigned": 0,
        "open": 0,
        "in_progress": 0,
        "blocked": 0,
        "completed": 0,
        "overdue": 0,
        "due_today": 0,
        "clients": set(),
        "assignees": set(),
    }

    for task in tasks:
        status = (task.status or "pending").strip().lower()
        is_closed = status in CLOSED_TASK_STATUSES
        target = getattr(task, "internal_target_date", None)
        client = getattr(task, "client", None)
        assignee = getattr(task, "assigned_to", None)
        subscription = getattr(task, "subscription", None)

        if client and getattr(client, "id", None):
            summary["clients"].add(client.id)
        if assignee and getattr(assignee, "id", None):
            summary["assignees"].add(assignee.id)
        if not is_closed:
            summary["open"] += 1
        if not getattr(task, "assigned_to_user_id", None) and not is_closed:
            summary["unassigned"] += 1
        if status == "in_progress":
            summary["in_progress"] += 1
        if status == "blocked":
            summary["blocked"] += 1
        if status == "completed":
            summary["completed"] += 1
        if target and target < today and not is_closed:
            summary["overdue"] += 1
        if target and target == today and not is_closed:
            summary["due_today"] += 1

        task.status_label = _task_status_label(task)
        task.priority_label = _task_priority_label(task)
        task.date_bucket = _date_bucket(task, today)
        task.is_overdue = bool(target and target < today and not is_closed)
        task.is_due_today = bool(target and target == today and not is_closed)
        task.engagement_label = _subscription_label(subscription, task)
        task.client_display = getattr(client, "client_name", None) or "Unlinked Client"
        task.client_code_display = getattr(client, "client_code", None) or ""
        task.assignee_display = getattr(assignee, "full_name", None) or getattr(assignee, "email", None) or "Unassigned"
        task.comment_count = len([c for c in getattr(task, "comments", []) if not getattr(c, "is_deleted", False)])

        if not getattr(task, "assigned_to_user_id", None) and not is_closed:
            bucket = "unassigned"
        elif status == "pending":
            bucket = "assigned"
        elif status == "in_progress":
            bucket = "in_progress"
        elif status == "blocked":
            bucket = "blocked"
        else:
            bucket = "ready_review"
        lookup[bucket]["tasks"].append(task)

    summary["clients"] = len(summary["clients"])
    summary["assignees"] = len(summary["assignees"])
    for column in columns:
        column["count"] = len(column["tasks"])
    return {"summary": summary, "columns": columns, "q": q, "selected_assigned_to_user_id": assigned_to_user_id, "today": today, "financial_year": financial_year}


@router.get("/dashboard")
def manager_dashboard(request: Request, q: str = "", assigned_to_user_id: int = 0):
    db = CommonSessionLocal()
    try:
        current_user = get_current_user(request, db=db)
        if not current_user:
            return _redirect_login()
        try:
            require_permission(db, current_user, "employees.work.manage")
        except Exception:
            return _redirect_denied()
        scope = build_employee_scope(
            db,
            current_user,
            tenant_id=request.session.get("active_tenant_id") or current_user.tenant_id,
            branch_id=request.session.get("active_branch_id"),
        )
        assignee_id = int(assigned_to_user_id or 0) or None
        financial_year = _active_financial_year(request)
        payload = build_manager_workspace_payload(db, scope, q=q, assigned_to_user_id=assignee_id, financial_year=financial_year)
        return _render(
            request,
            "modules/managers/templates/managers/dashboard.html",
            db,
            current_user,
            title="Manager Workspace",
            payload=payload,
            assignable_users=list_employee_work_assignable_users(db, scope),
            q=q,
            selected_assigned_to_user_id=assignee_id,
            errors=[],
            financial_year=financial_year,
        )
    finally:
        db.close()


@router.get("/work")
def manager_work_board(request: Request, q: str = "", assigned_to_user_id: int = 0):
    db = CommonSessionLocal()
    try:
        current_user = get_current_user(request, db=db)
        if not current_user:
            return _redirect_login()
        try:
            require_permission(db, current_user, "employees.work.manage")
        except Exception:
            return _redirect_denied()
        scope = build_employee_scope(
            db,
            current_user,
            tenant_id=request.session.get("active_tenant_id") or current_user.tenant_id,
            branch_id=request.session.get("active_branch_id"),
        )
        assignee_id = int(assigned_to_user_id or 0) or None
        financial_year = _active_financial_year(request)
        payload = build_manager_workspace_payload(db, scope, q=q, assigned_to_user_id=assignee_id, financial_year=financial_year)
        return _render(
            request,
            "modules/managers/templates/managers/work_board.html",
            db,
            current_user,
            title="Team Work Board",
            payload=payload,
            assignable_users=list_employee_work_assignable_users(db, scope),
            q=q,
            selected_assigned_to_user_id=assignee_id,
            errors=[],
            financial_year=financial_year,
        )
    finally:
        db.close()
