import plotly.graph_objects as go


FONT = {"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"}


def load_data():
    return [
        ("North Cove", 2.4, 4.1, 14),
        ("Ferry Pier", 3.1, 2.9, 22),
        ("Midchannel", 4.3, 2.6, 10),
        ("Outer Spit", 5.1, 1.9, 7),
        ("South Bank", 3.4, 1.5, 17),
        ("Bay Mouth", 5.5, 3.3, 8),
    ]


def value_table(data):
    return {
        "columns": ["Station", "East (km)", "North (km)", "Turbidity (NTU)"],
        "rows": [list(row) for row in data],
    }


def _harbor_turbidity(data, *, show_context):
    stations, east, north, turbidity = zip(*data, strict=True)
    fig = go.Figure()
    if show_context:
        fig.add_scatter(
            x=[0, 0, 1.8, 2.0, 2.7, 2.4, 3.0, 3.1, 4.8, 4.5, 2.2, 0],
            y=[0, 5, 5, 4.0, 3.5, 2.9, 2.3, 1.2, 1.15, 0.65, 0, 0],
            mode="lines",
            fill="toself",
            fillcolor="#e8e4da",
            line={"color": "#8e887b", "width": 1},
            hoverinfo="skip",
        )
        for x, y, label in (
            (1.0, 2.4, "Harbor town"),
            (3.7, 3.8, "East Bay"),
            (5.7, 4.65, "North"),
        ):
            fig.add_annotation(x=x, y=y, text=label, showarrow=False)
        fig.add_shape(type="line", x0=4.9, x1=5.9, y0=0.45, y1=0.45)
        fig.add_annotation(x=5.4, y=0.65, text="1 km", showarrow=False)
    fig.add_scatter(
        x=east,
        y=north,
        mode="markers",
        text=stations,
        marker={
            "size": 17,
            "color": turbidity,
            "cmin": 0,
            "cmax": 25,
            "colorscale": [[0, "#edf5fa"], [1, "#10456e"]],
            "line": {"color": "#36576a", "width": 1},
            "showscale": True,
            "colorbar": {"title": "NTU", "thickness": 12},
        },
        hovertemplate="%{text}: %{marker.color} NTU<extra></extra>",
    )
    if show_context:
        for x, y, label in ((3.1, 2.9, "Ferry Pier"), (5.1, 1.9, "Outer Spit")):
            fig.add_annotation(x=x, y=y, text=label, yshift=-19, showarrow=False)
    fig.update_layout(
        template="simple_white",
        font=FONT,
        title="Turbidity at harbor sampling stations",
        plot_bgcolor="#f3f8fb" if show_context else "#ffffff",
        showlegend=False,
        xaxis={"visible": False, "range": [0, 6.25]},
        yaxis={"visible": False, "range": [0, 5], "scaleanchor": "x", "scaleratio": 1},
        height=390,
        margin={"l": 25, "r": 65, "t": 58, "b": 24},
    )
    return fig


def make_after(data) -> go.Figure:
    return _harbor_turbidity(data, show_context=True)


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