from flask import flash, redirect, render_template, request, url_for

from app.admin import admin_blueprint
from app.admin.auth import admin_login_required
from models.user_model import get_event_config, update_event_config


@admin_blueprint.route("/event-config", methods=["GET", "POST"])
@admin_login_required
def event_config_page():
    if request.method == "POST":
        event_name = (request.form.get("event_name") or "").strip()
        event_subtitle = (request.form.get("event_subtitle") or "").strip()
        venue = (request.form.get("venue") or "").strip()
        start_date = (request.form.get("start_date") or "").strip() or None
        end_date = (request.form.get("end_date") or "").strip() or None

        if not event_name:
            flash("Event name is required.", "error")
            return redirect(url_for("admin.event_config_page"))

        try:
            update_event_config(event_name, event_subtitle, venue, start_date, end_date)
            flash("Event configuration updated successfully.", "success")
        except Exception as exc:
            flash(f"Failed to update event configuration: {exc}", "error")

        return redirect(url_for("admin.event_config_page"))

    event = get_event_config()
    return render_template("event_config.html", event=event)
