import plotly.graph_objects as go


def load_data():
    return [
        ("Ash", 120, 108),
        ("Birch", 180, 172),
        ("Cedar", 150, 128),
        ("Elm", 160, 154),
        ("Pine", 200, 190),
    ]


def value_table(data):
    return {
        "columns": ["Plant", "Target output (units)", "Actual output (units)"],
        "rows": [list(row) for row in data],
    }


def _output_chart_layout(fig, title: str, axis_title: str, upper_limit: int) -> go.Figure:
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": title, "x": 0.08},
        xaxis={"title": axis_title, "range": [0, upper_limit]},
        yaxis={"autorange": "reversed"},
        margin={"l": 78, "r": 30, "t": 90, "b": 62},
    )
    return fig


def make_after(data) -> go.Figure:
    shortfalls = sorted(
        ((plant, target - actual) for plant, target, actual in data),
        key=lambda row: row[1],
        reverse=True,
    )
    plants, gaps = zip(*shortfalls, strict=True)
    fig = go.Figure(
        go.Bar(
            x=gaps,
            y=plants,
            orientation="h",
            marker_color="#246487",
            texttemplate="%{x}",
            textposition="outside",
        )
    )
    return _output_chart_layout(fig, "Production shortfall by plant", "Units below target", 26)


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