import plotly.express as px


import plotly.graph_objects as go


def load_data():
    frame = px.data.gapminder()
    americas = frame[frame["continent"] == "Americas"]
    y1982 = americas[americas["year"] == 1982].set_index("country")["lifeExp"]
    y2007 = americas[americas["year"] == 2007].set_index("country")["lifeExp"]
    picks = [
        "Haiti",
        "Bolivia",
        "Guatemala",
        "Peru",
        "Brazil",
        "Colombia",
        "Mexico",
        "Argentina",
        "Chile",
        "Costa Rica",
        "United States",
        "Canada",
    ]
    rows = [
        (country, round(float(y1982[country]), 1), round(float(y2007[country]), 1))
        for country in picks
    ]
    rows.sort(key=lambda item: item[2])
    return rows


def value_table(data):
    return {
        "columns": ["Country", "1982 life expectancy (years)", "2007 life expectancy (years)", "Gain (years)"],
        "rows": [[c, a, b, round(b - a, 1)] for c, a, b in reversed(data)],
    }


def make_after(data) -> go.Figure:
    x_vals = [row[1] for row in data]
    y_vals = [row[2] for row in data]
    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=[50, 83],
            y=[50, 83],
            mode="lines",
            name="No change (y = x)",
            line={"color": "#94a3b8", "width": 1.5, "dash": "dash"},
            showlegend=False,
        )
    )
    fig.add_trace(
        go.Scatter(
            x=x_vals,
            y=y_vals,
            mode="markers",
            name="Countries",
            marker={"size": 9, "color": "#0072B2"},
            showlegend=False,
        )
    )
    callouts = {
        "Bolivia": (6, 6),
        "Haiti": (6, -8),
        "Peru": (6, 6),
        "Canada": (-8, 10),
        "United States": (6, -10),
    }
    for country, v82, v07 in data:
        if country in callouts:
            dx, dy = callouts[country]
            fig.add_annotation(
                x=v82,
                y=v07,
                text=country,
                showarrow=False,
                xshift=dx,
                yshift=dy,
                xanchor="left" if dx > 0 else "right",
                font={"size": 11, "color": "#334155"},
            )
    fig.add_annotation(
        x=75,
        y=72,
        text="No change (y = x)",
        showarrow=False,
        font={"size": 11, "color": "#64748b"},
    )
    fig.update_layout(
        template="simple_white",
        showlegend=False,
        xaxis_title="1982 life expectancy (years)",
        yaxis_title="2007 life expectancy (years)",
        xaxis_range=[49, 84],
        yaxis_range=[49, 84],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 64, "r": 24, "t": 28, "b": 48},
    )
    return fig


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