"""Results page: charts and model outputs."""

import streamlit as st

from frontend import api_client
from frontend.components.charts import (
    allocation_pie_charts,
    channel_contribution_waterfall,
    roas_bar_chart,
    saturation_curves,
)


def show_results_page():
    project = st.session_state.get("current_project")
    if not project:
        st.warning("No project selected")
        return

    st.title(f"Results: {project['name']}")

    col1, col2 = st.columns(2)
    with col1:
        if st.button("< Back to Dashboard"):
            st.session_state["page"] = "dashboard"
            st.rerun()
    with col2:
        if st.button("View Recommendations"):
            st.session_state["page"] = "recommendations"
            st.rerun()

    # Fetch latest run
    resp = api_client.get(f"/projects/{project['id']}/runs/latest")
    if resp.status_code != 200:
        st.warning("No model results yet. Train a model first.")
        return

    run = resp.json()
    if run["status"] != "completed":
        st.info(f"Model status: {run['status']}")
        return

    # Duration info
    st.caption(f"Training completed in {run.get('duration_secs', 0):.0f} seconds")

    # Channel contributions waterfall
    if run.get("channel_contributions"):
        st.plotly_chart(
            channel_contribution_waterfall(run["channel_contributions"]),
            use_container_width=True,
        )

    # ROAS bar chart
    if run.get("roas_estimates"):
        st.plotly_chart(
            roas_bar_chart(run["roas_estimates"], roas_ci=run.get("roas_ci")),
            use_container_width=True,
        )

    # Saturation curves
    if run.get("saturation_curves"):
        st.plotly_chart(
            saturation_curves(run["saturation_curves"]),
            use_container_width=True,
        )

    # Budget allocation comparison
    if run.get("current_allocation") and run.get("optimal_allocation"):
        st.subheader("Budget Allocation: Current vs Optimal")
        col1, col2 = st.columns(2)
        fig_current, fig_optimal = allocation_pie_charts(
            run["current_allocation"], run["optimal_allocation"]
        )
        with col1:
            st.plotly_chart(fig_current, use_container_width=True)
        with col2:
            st.plotly_chart(fig_optimal, use_container_width=True)

        if run.get("expected_lift_pct"):
            st.metric("Expected Improvement", f"+{run['expected_lift_pct']:.1f}%")
