import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    europe = frame[(frame["year"] == 2007) & (frame["continent"] == "Europe")].nlargest(12, "lifeExp")
    rows = [
        (str(country), round(float(life), 2))
        for country, life in europe[["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.Scatter(
            x=values,
            y=countries,
            mode="markers",
            marker={"size": 9, "color": "#0072B2"},
        )
    )
    for country, val in data:
        fig.add_shape(
            type="line",
            x0=78.8,
            x1=val,
            y0=country,
            y1=country,
            line={"color": "#cbd5e1", "width": 1, "dash": "dot"},
            layer="below",
        )
        fig.add_annotation(
            x=val,
            y=country,
            text=f"{val:.1f}",
            showarrow=False,
            xanchor="left",
            xshift=8,
            font={"size": 11, "color": "#334155"},
        )
    fig.update_layout(
        template="simple_white",
        xaxis_title="Life expectancy in 2007 (years)",
        xaxis_range=[78.8, 82.6],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 110, "r": 40, "t": 28, "b": 48},
    )
    return fig


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