import plotly.graph_objects as go


Row = tuple[str, str, int]


def value_table(data: list[Row]) -> dict[str, list]:
    return {"columns": ["From", "To", "Parcels"], "rows": [list(row) for row in data]}


def _style_figure(fig: go.Figure, **layout: object) -> go.Figure:
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Parcel flow through sorting", "x": 0.02, "xanchor": "left"},
        margin={"l": 72, "r": 32, "t": 84, "b": 64},
        showlegend=False,
        **layout,
    )
    return fig


def load_data() -> list[Row]:
    return [
        ("Web orders", "Sorting", 60),
        ("Store orders", "Sorting", 40),
        ("Sorting", "City route", 65),
        ("Sorting", "Rural route", 25),
        ("Sorting", "Returns", 10),
    ]


def make_before(data: list[Row]) -> go.Figure:
    totals = {}
    for source, destination, count in data:
        if destination == "Sorting":
            totals[source] = count
            totals[destination] = totals.get(destination, 0) + count
        else:
            totals[destination] = count
    fig = go.Figure(
        go.Bar(
            x=list(totals.values()),
            y=list(totals),
            orientation="h",
            marker_color="#226391",
        )
    )
    return _style_figure(
        fig,
        xaxis={"title": "Parcels", "range": [0, 110]},
        yaxis={"autorange": "reversed", "automargin": True},
    )


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