import numpy as np


import plotly.express as px


import plotly.graph_objects as go


from plotly.subplots import make_subplots


def load_data():
    frame = px.data.gapminder()
    latest = frame[(frame["year"] == 2007) & (frame["continent"] != "Oceania")]
    rows = []
    for continent in ("Africa", "Asia", "Americas", "Europe"):
        group = latest[latest["continent"] == continent]
        rows.append(
            (
                continent,
                round(float(np.median(group["gdpPercap"])), 0),
                round(float(np.median(group["lifeExp"])), 1),
            )
        )
    return rows


def value_table(data):
    return {
        "columns": ["Continent", "Median GDP per capita (USD)", "Median life expectancy (years)"],
        "rows": [list(row) for row in data],
    }


def make_after(data) -> go.Figure:
    fig = make_subplots(
        rows=1,
        cols=2,
        subplot_titles=("A. Median GDP per capita (USD)", "B. Median life expectancy (years)"),
        horizontal_spacing=0.18,
    )
    palette = {
        "Africa": "#CC79A7",
        "Asia": "#E69F00",
        "Americas": "#009E73",
        "Europe": "#0072B2",
    }
    for continent, gdp, life in data:
        hue = palette[continent]
        fig.add_trace(
            go.Bar(
                x=[continent],
                y=[gdp],
                name=continent,
                marker={"color": hue},
                text=[f"{int(gdp):,}"],
                textposition="outside",
                showlegend=False,
            ),
            row=1,
            col=1,
        )
        fig.add_trace(
            go.Bar(
                x=[continent],
                y=[life],
                name=continent,
                marker={"color": hue},
                text=[f"{life:.1f}"],
                textposition="outside",
                showlegend=False,
            ),
            row=1,
            col=2,
        )
    fig.update_layout(
        template="simple_white",
        yaxis_range=[0, 34000],
        yaxis2_range=[0, 92],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 60, "r": 24, "t": 48, "b": 48},
    )
    return fig


if __name__ == "__main__":
    print(make_after(load_data()).to_json())
