import plotly.graph_objects as go


TITLE = "Household water consumption by district"


COLUMNS = ["District", "Mean daily consumption (L)", "Households"]


def load_data():
    return [
        ("South", 328, 124),
        ("East", 312, 112),
        ("West", 304, 110),
        ("North", 295, 106),
        ("Harbor", 276, 97),
    ]


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 consumption_table(data):
    rows = [
        (f"{district} [a]" if district == "Harbor" else district, liters, count)
        for district, liters, count in data
    ]
    return go.Figure(table_trace(COLUMNS, rows, ["left", "right", "right"], [1, 2.3, 1]))


def make_before(data) -> go.Figure:
    fig = consumption_table(data)
    table_note(
        fig,
        "Occupied households with a working meter in July. Shared meters excluded.<br>"
        "[a] Harbor covers July 8 to 31 due to a meter outage.",
    )
    return style_table(fig, TITLE, height=310, bottom=65)


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