import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    picks = ["Japan", "Switzerland", "Sweden", "Canada", "Germany", "United States"]
    latest = frame[(frame["year"] == 2007) & (frame["country"].isin(picks))]
    rows = [
        (str(country), round(float(life), 1))
        for country, life in latest[["country", "lifeExp"]].itertuples(index=False, name=None)
    ]
    rows.sort(key=lambda item: item[1])
    return rows


def value_table(data):
    return {
        "columns": ["Country", "Life expectancy in 2007 (years)"],
        "rows": [list(row) for row in reversed(data)],
    }


def make_after(data) -> go.Figure:
    countries = [row[0] for row in data]
    values = [row[1] for row in data]
    fig = go.Figure(
        go.Bar(
            x=values,
            y=countries,
            orientation="h",
            marker={"color": "#0072B2"},
            text=[f"{val:.1f}" for val in values],
            textposition="outside",
            textfont={"size": 12},
        )
    )
    fig.update_layout(
        template="simple_white",
        xaxis={
            "title": {"text": "Life expectancy in 2007 (years)", "font": {"size": 13}},
            "tickfont": {"size": 12},
            "range": [0, 92],
        },
        yaxis={"tickfont": {"size": 12}},
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 112, "r": 40, "t": 24, "b": 48},
    )
    return fig


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