from flask import jsonify, render_template, request

from app.admin import admin_blueprint
from app.admin.auth import admin_login_required
from models.user_model import add_day, add_day_event, get_all_day_events, get_day_events_grouped


@admin_blueprint.route("/day-events")
@admin_login_required
def day_events_page():
    """Render the Day Events management page."""
    return render_template("day_events.html")


@admin_blueprint.route("/api/day-events", methods=["GET"])
def api_get_day_events():
    """Public API endpoint to return all day events as a flat list for dropdown."""
    try:
        events = get_all_day_events()
        return jsonify([
            {
                "id": event["id"],
                "day": event["day"],
                "event_name": event["event_name"],
                "label": f"{event['day']} - {event['event_name']}" if event["event_name"] else event["day"]
            }
            for event in events
        ])
    except Exception as exc:
        return jsonify({"error": str(exc)}), 500


@admin_blueprint.route("/api/day-events/grouped", methods=["GET"])
@admin_login_required
def api_get_day_events_grouped():
    """Admin API endpoint to return all day events grouped by day."""
    try:
        grouped_events = get_day_events_grouped()
        return jsonify(grouped_events)
    except Exception as exc:
        return jsonify({"error": str(exc)}), 500


@admin_blueprint.route("/api/add-day", methods=["POST"])
@admin_login_required
def api_add_day():
    """API endpoint to add a new day."""
    try:
        data = request.get_json()
        day = (data.get("day") or "").strip()

        if not day:
            return jsonify({"error": "Day is required"}), 400

        add_day(day)
        return jsonify({"success": True, "day": day})
    except Exception as exc:
        return jsonify({"error": str(exc)}), 500


@admin_blueprint.route("/api/add-event", methods=["POST"])
@admin_login_required
def api_add_event():
    """API endpoint to add an event to a specific day."""
    try:
        data = request.get_json()
        day = (data.get("day") or "").strip()
        event_name = (data.get("event_name") or "").strip()

        if not day or not event_name:
            return jsonify({"error": "Day and event_name are required"}), 400

        add_day_event(day, event_name)
        return jsonify({"success": True, "day": day, "event_name": event_name})
    except Exception as exc:
        return jsonify({"error": str(exc)}), 500


@admin_blueprint.route("/api/update-event/<int:event_id>", methods=["PUT"])
@admin_login_required
def api_update_event(event_id):
    """API endpoint to update an event's name."""
    try:
        from config.db_config import get_db_connection

        data = request.get_json()
        event_name = (data.get("event_name") or "").strip()

        if not event_name:
            return jsonify({"error": "Event name is required"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "UPDATE day_events SET event_name = %s WHERE id = %s",
            (event_name, event_id)
        )
        conn.commit()
        cursor.close()
        conn.close()

        return jsonify({"success": True, "event_id": event_id, "event_name": event_name})
    except Exception as exc:
        return jsonify({"error": str(exc)}), 500


@admin_blueprint.route("/api/delete-event/<int:event_id>", methods=["DELETE"])
@admin_login_required
def api_delete_event(event_id):
    """API endpoint to delete an event."""
    try:
        from models.user_model import delete_day_event
        delete_day_event(event_id)
        return jsonify({"success": True, "event_id": event_id})
    except Exception as exc:
        return jsonify({"error": str(exc)}), 500