import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    selected = frame[frame["year"].isin([1952, 1972, 1992, 2007])]
    return list(
        selected[["country", "year", "gdpPercap", "lifeExp", "continent"]].itertuples(
            index=False, name=None
        )
    )


def value_table(data):
    return {
        "columns": ["Country", "Year", "Income per person", "Life expectancy (years)", "Continent"],
        "rows": [list(row) for row in data],
    }


def make_after(data) -> go.Figure:
    import pandas as pd

    frame = pd.DataFrame(
        data, columns=["Country", "Year", "Income per person", "Life expectancy", "Continent"]
    )
    fig = px.scatter(
        frame,
        x="Income per person",
        y="Life expectancy",
        facet_col="Year",
        facet_col_wrap=2,
        hover_name="Country",
        log_x=True,
        range_x=[200, 150000],
        range_y=[20, 90],
        template="simple_white",
        height=550,
        width=700,
    )
    fig.update_xaxes(title_text=None, nticks=3)
    fig.update_yaxes(title_text=None, nticks=4)
    fig.update_xaxes(title_text="Income per person", row=1)
    fig.update_yaxes(title_text="Life expectancy (years)", col=1)
    fig.update_layout(margin={"l": 62, "r": 20, "t": 38, "b": 62})
    fig.for_each_annotation(lambda note: note.update(text=note.text.split("=")[-1]))
    fig.update_layout(
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        colorway=["#3b82c4", "#d97706", "#14967f", "#8b5cf6", "#dc4c3e", "#78716c"],
    )
    return fig


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