"""Dashboard page and chart data endpoint."""

from flask import Blueprint, render_template, request, jsonify, g

from webapp.auth import login_required
from webapp.dates import resolve_date_range, PERIOD_PRESETS, DEFAULT_PERIOD, period_label
from icp_db import (
    get_kpi_summary,
    get_executive_leaderboard,
    get_posting_frequency,
    get_monthly_trends,
    get_status_distribution,
    get_recent_activity,
    get_top_engagers,
    get_top_companies,
    get_top_posts,
)

dashboard_bp = Blueprint("dashboard", __name__)


def _extract_date_params():
    """Extract and resolve date range from request.args."""
    return resolve_date_range(
        request.args.get("period"),
        request.args.get("date_from"),
        request.args.get("date_to"),
    )


@dashboard_bp.route("/")
@dashboard_bp.route("/dashboard")
@login_required
def index():
    db = g.db
    date_from, date_to, active_period = _extract_date_params()
    dr = {"date_from": date_from, "date_to": date_to}

    kpi = get_kpi_summary(db, **dr)
    leaderboard = get_executive_leaderboard(db, **dr)
    posting = get_posting_frequency(db, **dr)
    status_dist = get_status_distribution(db, **dr)
    activity = get_recent_activity(db, **dr)
    top_engagers = get_top_engagers(db, limit=10, **dr)
    top_companies = get_top_companies(db, limit=10, **dr)
    top_posts = get_top_posts(db, limit=5, **dr)

    # Monthly top performer
    top_performer = leaderboard[0] if leaderboard and leaderboard[0]["icp_this_month"] > 0 else None

    # Build chart data URL with date params
    chart_params = f"?period={active_period}"
    if active_period == "custom" and date_from and date_to:
        chart_params += f"&date_from={date_from.isoformat()}&date_to={date_to.isoformat()}"

    has_date_filter = active_period != "all"
    active_period_label = period_label(active_period)
    if active_period == "custom" and date_from and date_to:
        active_period_label = f"{date_from.isoformat()} to {date_to.isoformat()}"

    return render_template(
        "dashboard.html",
        kpi=kpi,
        leaderboard=leaderboard,
        posting=posting,
        status_dist=status_dist,
        activity=activity,
        top_engagers=top_engagers,
        top_companies=top_companies,
        top_posts=top_posts,
        top_performer=top_performer,
        period_presets=PERIOD_PRESETS,
        active_period=active_period,
        active_period_label=active_period_label,
        has_date_filter=has_date_filter,
        date_from=date_from,
        date_to=date_to,
        chart_data_url="/dashboard/charts-data" + chart_params,
    )


@dashboard_bp.route("/dashboard/charts-data")
@login_required
def charts_data():
    """JSON endpoint for Chart.js charts."""
    db = g.db
    date_from, date_to, active_period = _extract_date_params()
    dr = {"date_from": date_from, "date_to": date_to}

    leaderboard = get_executive_leaderboard(db, **dr)
    trends = get_monthly_trends(db, months=12, **dr)
    status_dist = get_status_distribution(db, **dr)

    return jsonify({
        "executive_bar": {
            "labels": [e["name"] for e in leaderboard],
            "data": [e["icp_this_month"] for e in leaderboard],
        },
        "monthly_trend": {
            "labels": [t["month"] for t in trends],
            "data": [t["count"] for t in trends],
        },
        "status_doughnut": {
            "labels": [s["status"] for s in status_dist],
            "data": [s["count"] for s in status_dist],
        },
    })
