import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    picks = [
        "Iceland",
        "Norway",
        "Sweden",
        "Spain",
        "Germany",
        "Japan",
        "United States",
        "China",
    ]
    latest = frame[(frame["year"] == 2007) & (frame["country"].isin(picks))]
    rows = [
        (str(country), int(pop))
        for country, pop in latest[["country", "pop"]].itertuples(index=False, name=None)
    ]
    rows.sort(key=lambda item: item[1])
    return rows


def value_table(data):
    return {
        "columns": ["Country", "Population (2007)"],
        "rows": [[country, f"{pop:,}"] for country, pop in data],
    }


def make_after(data) -> go.Figure:
    countries = [row[0] for row in data]
    pops = [row[1] for row in data]
    fig = go.Figure(
        go.Scatter(
            x=pops,
            y=countries,
            mode="markers",
            marker={"size": 10, "color": "#0072B2"},
        )
    )
    for country, pop in data:
        fig.add_shape(
            type="line",
            x0=150_000,
            x1=pop,
            y0=country,
            y1=country,
            line={"color": "#cbd5e1", "width": 1, "dash": "dot"},
            layer="below",
        )
        label = f"{pop / 1e6:.1f}M" if pop >= 1_000_000 else f"{pop / 1e3:.0f}k"
        fig.add_annotation(
            x=pop,
            y=country,
            text=label,
            showarrow=False,
            xanchor="left",
            xshift=8,
            font={"size": 11, "color": "#334155"},
        )
    fig.update_layout(
        template="simple_white",
        xaxis_type="log",
        xaxis_title="Population in 2007 (log scale)",
        xaxis_range=[5.15, 9.5],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 110, "r": 48, "t": 28, "b": 48},
    )
    return fig


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