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_before(data):
    import pandas as pd
    import plotly.express as px

    branches, issued, prior, targets = zip(*data, strict=True)
    fig = go.Figure(
        go.Bar(
            x=branches,
            y=issued,
            name="This month",
            marker_pattern_shape="/",
            marker_color="#999999",
        )
    )
    frame = pd.DataFrame({"Branch": branches, "Previous": prior, "Target": targets})
    series = px.line(
        frame.melt(id_vars="Branch", var_name="Series", value_name="Loans"),
        x="Branch",
        y="Loans",
        color="Series",
        line_dash="Series",
    )
    fig.add_traces(series.data)
    for index, background in enumerate(["#f5f5f5", "#555555", "#f5f5f5", "#555555"]):
        fig.add_vrect(
            x0=index - 0.48, x1=index + 0.48, fillcolor=background, line_width=0, layer="below"
        )
    fig.update_layout(
        template="simple_white",
        title_text="Branch lending",
        yaxis=dict(type="log", title="Loans"),
        annotations=[
            {"x": "East", "y": 1.98, "text": "96", "showarrow": False},
            {"x": "East", "y": 2, "text": "100", "showarrow": False},
        ],
    )
    return fig


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