import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    latest = frame[frame["year"] == 2007]
    return [
        (str(iso), str(country), round(float(pop) * float(income) / 1e9, 1), round(float(income)))
        for iso, country, pop, income in latest[
            ["iso_alpha", "country", "pop", "gdpPercap"]
        ].itertuples(index=False, name=None)
    ]


def value_table(data):
    ordered = sorted(data, key=lambda item: item[3], reverse=True)
    return {
        "columns": [
            "ISO",
            "Country",
            "Total income (billion dollars)",
            "Income per person (dollars)",
        ],
        "rows": [list(row) for row in ordered[:10]],
    }


def _income_map(data, column, title, unit) -> go.Figure:
    fig = go.Figure(
        go.Choropleth(
            locations=[row[0] for row in data],
            z=[row[column] for row in data],
            text=[row[1] for row in data],
            colorscale=[[0, "#eef4f8"], [1, "#0f3d5e"]],
            colorbar={"title": unit, "thickness": 12},
            marker_line_color="#ffffff",
            marker_line_width=0.4,
        )
    )
    fig.update_layout(
        template="simple_white",
        title={"text": title, "x": 0.02},
        geo={
            "projection": {"type": "natural earth"},
            "showframe": False,
            "showcoastlines": False,
            "bgcolor": "rgba(0, 0, 0, 0)",
        },
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 16, "r": 16, "t": 64, "b": 16},
    )
    return fig


def make_before(data) -> go.Figure:
    return _income_map(data, 2, "Total national income in 2007", "Billion dollars")


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