import plotly.graph_objects as go


TITLE = "Meter calibration readings"


COLUMNS = ["Meter", "Inspection date", "Error (mm)"]


def load_data():
    return [
        ("M01", "2025-04-03", 0.04),
        ("M02", "2025-04-03", -0.03),
        ("M03", "2025-04-05", 0.1),
        ("M04", "2025-04-05", 0.08),
        ("M05", "2025-04-07", -0.02),
    ]


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 make_before(data) -> go.Figure:
    rows = [
        (meter, date[5:7] + "/" + date[8:10] + "/" + date[2:4], f"{round(error, 1) + 0.0:.1f}")
        for meter, date, error in data
    ]
    return style_table(
        go.Figure(table_trace(COLUMNS, rows, ["left", "left", "right"], [1, 1.5, 1])), TITLE
    )


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