from flask import jsonify, render_template
from datetime import date, timedelta

from app.admin import admin_blueprint
from app.admin.auth import admin_login_required
from models.user_model import (
    get_dashboard_chart_data,
    get_dashboard_counts,
    get_event_config,
    get_remaining_visitors,
    get_site_assets,
    get_events,
)
from models.email_queries import get_email_delivery_stats, get_daywise_email_stats


@admin_blueprint.route("/dashboard")
@admin_login_required
def dashboard_page():
    return render_template(
        "dashboard.html",
        stats=get_dashboard_counts(),
        chart_data=get_dashboard_chart_data(),
        site_assets=get_site_assets(),
        event_data=get_event_config(),
        day_events=get_events(),
    )


@admin_blueprint.route("/api/emails/stats", methods=["GET"])
@admin_login_required
def api_email_stats():
    """Return email delivery stats: total, sent, remaining."""
    try:
        data = get_email_delivery_stats()
        for row in data.get("sent", []):
            if row.get("last_sent_at") and hasattr(row["last_sent_at"], "isoformat"):
                row["last_sent_at"] = row["last_sent_at"].isoformat()
        return jsonify(data)
    except Exception as exc:
        return jsonify({"error": str(exc), "sent": [], "remaining": [], "total_users_with_matches": 0, "total_emails_sent": 0}), 500


@admin_blueprint.route("/api/daywise-email-stats", methods=["GET"])
@admin_login_required
def api_daywise_email_stats():
    """Return per-day email stats based on event start/end date."""
    try:
        event = get_event_config()

        if not event:
            return jsonify({"days": [], "total_matched_users": 0, "reason": "no_event"})

        start = event.get("start_date")
        end = event.get("end_date")

        if not start or not end:
            return jsonify({"days": [], "total_matched_users": 0, "reason": "no_dates",
                           "event_name": event.get("event_name")})

        event_name = event.get("event_name", "Event")

        # Build list of days between start and end
        days_list = []
        current = start
        while current <= end:
            days_list.append(current)
            current += timedelta(days=1)

        # Get email stats per day
        stats = get_daywise_email_stats(start, end)
        sent_by_day = stats.get("sent_by_day", {})
        total_matched = stats.get("total_matched_users", 0)

        result = []
        for idx, d in enumerate(days_list):
            day_str = str(d)
            day_data = sent_by_day.get(day_str, {})
            result.append({
                "date": d.strftime("%b %d, %Y"),
                "date_raw": day_str,
                "day_num": idx + 1,
                "event_name": event_name,
                "emails_sent": day_data.get("emails_sent", 0),
                "users_reached": day_data.get("users_reached", 0),
            })

        return jsonify({"days": result, "total_matched_users": total_matched})
    except Exception as exc:
        return jsonify({"error": str(exc), "days": [], "total_matched_users": 0}), 500


@admin_blueprint.route("/api/remaining-visitors", methods=["GET"])
@admin_login_required
def api_remaining_visitors():
    """Fetch visitors who haven't completed face registration."""
    try:
        remaining = get_remaining_visitors()
        return jsonify({"count": len(remaining), "data": remaining})
    except Exception as exc:
        return jsonify({"count": 0, "data": [], "error": str(exc)})