import plotly.graph_objects as go


import plotly.io as pio


INK = "#1C1917"


MUTED = "#57534E"


WARM_EDITORIAL_PALETTE = [
    "#0F766E",
    "#C2410C",
    "#1D4ED8",
    "#A16207",
    "#7E22CE",
    "#475569",
    "#0369A1",
    "#1C1917",
]


CANVAS = "#FFF7ED"


RULE = "#E7DDD2"


pio.templates["warm_editorial"] = go.layout.Template(
    layout=go.Layout(
        colorway=WARM_EDITORIAL_PALETTE,
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "size": 13, "color": INK},
        title={
            "x": 0,
            "xanchor": "left",
            "font": {"family": "Georgia, 'Times New Roman', serif", "size": 18, "color": INK},
        },
        paper_bgcolor=CANVAS,
        plot_bgcolor=CANVAS,
        xaxis={
            "showgrid": False,
            "showline": True,
            "linecolor": "#A8A29E",
            "tickcolor": "#A8A29E",
            "tickfont": {"color": MUTED},
            "automargin": True,
        },
        yaxis={
            "showgrid": True,
            "gridcolor": RULE,
            "gridwidth": 1,
            "showline": False,
            "tickcolor": "#A8A29E",
            "tickfont": {"color": MUTED},
            "zeroline": False,
            "automargin": True,
        },
    )
)


def load_data():
    return [("Central", 18.5), ("East", 24.0), ("Harbor", 42.5), ("West", 15.0)]


def make_after(data):
    branches, amounts = zip(*sorted(data, key=lambda row: -row[1]), strict=True)
    total = sum(amounts)
    fig = go.Figure(go.Bar(x=branches, y=amounts, marker_color=WARM_EDITORIAL_PALETTE[0]))
    for branch, amount in zip(branches, amounts, strict=True):
        fig.add_annotation(
            x=branch,
            y=amount,
            text=f"${amount:g}k<br>{100 * amount / total:g}%",
            yshift=18,
            showarrow=False,
        )
    fig.update_layout(
        template="warm_editorial",
        title_text=f"Branch grants total ${total:g},000",
        yaxis_title="Grant ($000)",
        yaxis_range=[0, 54],
    )
    return fig


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