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 [
        ("North", 28, 24, 35),
        ("Harbor", 55, 47, 60),
        ("East", 96, 93, 100),
        ("West", 38, 40, 45),
    ]


def make_after(data):
    from plotly.subplots import make_subplots

    fig = make_subplots(
        rows=1, cols=3, shared_yaxes=True, subplot_titles=("Previous month", "This month", "Target")
    )
    branches = [row[0] for row in data]
    for col, field in enumerate([2, 1, 3], start=1):
        counts = [row[field] for row in data]
        fig.add_trace(
            go.Bar(
                x=counts,
                y=branches,
                orientation="h",
                marker_color=WARM_EDITORIAL_PALETTE[0],
                text=counts,
                textposition="outside",
                cliponaxis=False,
            ),
            row=1,
            col=col,
        )
    fig.update_xaxes(title_text="Loans", range=[0, 120], tickvals=[0, 50, 100])
    fig.update_yaxes(autorange="reversed")
    fig.update_layout(
        template="warm_editorial",
        title_text="East came within four loans of its target",
        showlegend=False,
        margin=dict(t=88),
    )
    return fig


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