import plotly.graph_objects as go


def load_data():
    """Return forecast demand and 80 percent prediction limits in units."""
    return [
        ("Monday", 82, 65, 99),
        ("Tuesday", 86, 72, 100),
        ("Wednesday", 91, 72, 110),
        ("Thursday", 97, 71, 123),
        ("Friday", 104, 79, 129),
    ]


def value_table(data):
    return {
        "columns": ["Day", "Forecast units", "80% lower limit", "80% upper limit"],
        "rows": [list(row) for row in data],
    }


def _sales_forecast_figure(data, show_intervals):
    day, estimate, lower, upper = zip(*data, strict=True)
    points = go.Scatter(
        x=estimate,
        y=day,
        mode="markers",
        marker={"color": "#22628a", "size": 9},
        hovertemplate="%{y}<br>Forecast %{x} units<extra></extra>",
    )
    subtitle = "Points and 80% prediction intervals" if show_intervals else "Point forecasts"
    if show_intervals:
        points.error_x = {
            "type": "data",
            "symmetric": False,
            "array": [hi - value for hi, value in zip(upper, estimate, strict=True)],
            "arrayminus": [value - lo for value, lo in zip(estimate, lower, strict=True)],
            "color": "#22628a",
            "width": 5,
        }
        points.customdata = list(zip(lower, upper, strict=True))
        points.hovertemplate = (
            "%{y}<br>Forecast %{x} units<br>80% interval %{customdata[0]} to %{customdata[1]} units"
            "<extra></extra>"
        )
    fig = go.Figure(points)
    fig.add_vline(
        x=100,
        line_color="#687887",
        line_dash="dot",
        annotation_text="100 units in stock",
        annotation_position="top left",
    )
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Daily demand forecast", "subtitle": {"text": subtitle}},
        xaxis={"title": "Demand (units)", "range": [60, 135]},
        yaxis_autorange="reversed",
        margin={"l": 100, "r": 24, "t": 85, "b": 60},
    )
    return fig


def make_after(data) -> go.Figure:
    return _sales_forecast_figure(data, show_intervals=True)


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