import plotly.graph_objects as go


def load_data():
    return [
        ("Harbor", 400, 24),
        ("Hill", 100, 17),
        ("Market", 300, 21),
        ("Park", 180, 18),
        ("Station", 500, 25),
    ]


def value_table(data):
    return {
        "columns": ["Outlet", "Orders", "Late orders"],
        "rows": [list(row) for row in data],
    }


def _late_order_chart(outlets, values, axis_title, axis_range, tickformat) -> go.Figure:
    fig = go.Figure(go.Bar(x=values, y=outlets, orientation="h", marker_color="#246487"))
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Late orders by outlet", "x": 0.08},
        xaxis={"title": axis_title, "range": axis_range, "tickformat": tickformat},
        yaxis={"autorange": "reversed"},
        margin={"l": 82, "r": 28, "t": 72, "b": 64},
    )
    return fig


def make_after(data) -> go.Figure:
    ranked_rates = sorted(
        ((outlet, late / orders) for outlet, orders, late in data),
        key=lambda row: row[1],
        reverse=True,
    )
    outlets, rates = zip(*ranked_rates, strict=True)
    fig = _late_order_chart(
        outlets, rates, "Share of each outlet's orders that were late", [0, 0.2], ".0%"
    )
    fig.update_layout(title_text="Where was an order most likely to be late?")
    return fig


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