import plotly.graph_objects as go


Row = tuple[str, str, int]


def value_table(data: list[Row]) -> dict[str, list]:
    return {"columns": ["From", "To", "Travel time (min)"], "rows": [list(row) for row in data]}


def _style_figure(fig: go.Figure, **layout: object) -> go.Figure:
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": "Travel time between campus buildings", "x": 0.02, "xanchor": "left"},
        margin={"l": 72, "r": 32, "t": 84, "b": 64},
        showlegend=False,
        **layout,
    )
    return fig


def load_data() -> list[Row]:
    return [
        ("Library", "Lab", 4),
        ("Library", "Hall", 6),
        ("Library", "Gym", 9),
        ("Lab", "Library", 4),
        ("Lab", "Hall", 5),
        ("Lab", "Gym", 7),
        ("Hall", "Library", 6),
        ("Hall", "Lab", 5),
        ("Hall", "Gym", 3),
        ("Gym", "Library", 9),
        ("Gym", "Lab", 7),
        ("Gym", "Hall", 3),
    ]


def make_after(data: list[Row]) -> go.Figure:
    buildings = list(dict.fromkeys(row[0] for row in data))
    minutes = {(origin, destination): value for origin, destination, value in data}
    matrix = [
        [minutes.get((origin, destination)) for destination in buildings] for origin in buildings
    ]
    fig = go.Figure(
        go.Heatmap(
            x=buildings,
            y=buildings,
            z=matrix,
            colorscale=[[0, "#f2f7fb"], [1, "#86aecb"]],
            zmin=0,
            zmax=9,
            xgap=2,
            ygap=2,
            text=[["" if value is None else str(value) for value in row] for row in matrix],
            texttemplate="%{text}",
            textfont={"color": "#172b3b"},
            showscale=False,
            hoverongaps=False,
            hovertemplate="%{y} to %{x}: %{z} min<extra></extra>",
        )
    )
    return _style_figure(
        fig,
        xaxis={"title": "Destination", "tickangle": 0},
        yaxis={"title": "Origin", "autorange": "reversed"},
        plot_bgcolor="#ffffff",
    )


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