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_before(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,
    )
    left_colors = ["#0072B2", "#E69F00", "#009E73", "#CC79A7"]
    right_colors = ["#CC79A7", "#009E73", "#E69F00", "#0072B2"]
    for idx, (continent, gdp, life) in enumerate(data):
        fig.add_trace(
            go.Bar(
                x=[continent],
                y=[gdp],
                name=continent,
                marker={"color": left_colors[idx]},
                showlegend=False,
            ),
            row=1,
            col=1,
        )
        fig.add_trace(
            go.Bar(
                x=[continent],
                y=[life],
                name=continent,
                marker={"color": right_colors[idx]},
                showlegend=False,
            ),
            row=1,
            col=2,
        )
    fig.update_layout(
        template="simple_white",
        yaxis_range=[0, 32000],
        yaxis2_range=[0, 90],
        margin={"l": 60, "r": 24, "t": 48, "b": 48},
    )
    return fig


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