import plotly.graph_objects as go


TITLE = "Delivery time regression"


COLUMNS = ["Predictor", "Model 1", "Model 2"]


def load_data():
    return [
        ("Intercept", 22.0, 18.5),
        ("Distance per km", 1.8, 1.4),
        ("Express service", -8.2, -7.6),
        ("Evening pickup", None, 4.1),
        ("Parcel weight per kg", None, 0.6),
    ]


def value_table(data):
    return {"columns": COLUMNS, "rows": [list(row) for row in data]}


def table_trace(columns, rows, align, widths, *, row_height=28, header_height=34, fill="#ffffff"):
    return go.Table(
        columnwidth=widths,
        header={
            "values": [f"<b>{column}</b>" for column in columns],
            "align": align,
            "height": header_height,
            "fill": {"color": "#eef2f6"},
            "line": {"width": 0},
            "font": {"color": "#1f2937", "size": 13},
        },
        cells={
            "values": list(zip(*rows, strict=True)),
            "align": align,
            "height": row_height,
            "fill": {"color": fill},
            "line": {"width": 0},
            "font": {"color": "#1f2937", "size": 13},
        },
    )


def style_table(fig, title, *, height=280, top=60, bottom=16):
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": title, "x": 0.04, "xanchor": "left"},
        height=height,
        margin={"l": 24, "r": 24, "t": top, "b": bottom},
    )
    return fig


def table_note(fig, text, *, y=0, anchor="top", shift=-8):
    fig.add_annotation(
        text=text,
        x=0,
        y=y,
        xref="paper",
        yref="paper",
        xanchor="left",
        yanchor=anchor,
        yshift=shift,
        align="left",
        showarrow=False,
        font={"size": 12, "color": "#475569"},
    )


def make_after(data) -> go.Figure:
    rows = [
        (label, "Omitted" if basic is None else f"{basic:.1f}", f"{adjusted:.1f}")
        for label, basic, adjusted in data
    ]
    columns = [COLUMNS[0], "1. Route and service", "2. Adds time and weight"]
    fig = go.Figure(table_trace(columns, rows, ["left", "right", "right"], [1.5, 1.4, 1.6]))
    table_note(
        fig,
        "Both models use ordinary least squares to estimate delivery time in minutes.<br>"
        "Reference levels are standard service and daytime pickup.",
    )
    return style_table(fig, TITLE, height=300, bottom=63)


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