import numpy as np


import plotly.express as px


import plotly.graph_objects as go


def load_data():
    tips = px.data.tips()
    rows = []
    for (day, time), group in tips.groupby(["day", "time"]):
        if len(group) < 5:
            continue
        vals = group["total_bill"].to_numpy(dtype=float)
        mean = float(np.mean(vals))
        se = float(np.std(vals, ddof=1) / np.sqrt(len(vals)))
        rows.append(
            (
                f"{day} {time}",
                len(vals),
                round(mean, 2),
                round(0.674 * se, 2),
                round(1.96 * se, 2),
            )
        )
    rows.sort(key=lambda item: item[2])
    return rows


def value_table(data):
    return {
        "columns": ["Service", "Checks", "Mean bill (USD)", "50% CI half-width", "95% CI half-width"],
        "rows": [list(row) for row in data],
    }


def make_after(data) -> go.Figure:
    labels = [row[0] for row in data]
    means = [row[2] for row in data]
    ci50 = [row[3] for row in data]
    ci95 = [row[4] for row in data]
    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=means,
            y=labels,
            mode="markers",
            name="95% CI",
            marker={"size": 1, "color": "rgba(0, 0, 0, 0)"},
            error_x={
                "type": "data",
                "array": ci95,
                "visible": True,
                "color": "#56B4E9",
                "thickness": 2,
                "width": 0,
            },
        )
    )
    fig.add_trace(
        go.Scatter(
            x=means,
            y=labels,
            mode="markers",
            name="50% CI and mean",
            marker={"size": 9, "color": "#1f2937"},
            error_x={
                "type": "data",
                "array": ci50,
                "visible": True,
                "color": "#0072B2",
                "thickness": 6,
                "width": 0,
            },
        )
    )
    fig.add_annotation(
        x=means[-1] + ci95[-1] + 0.5,
        y=labels[-1],
        text="Thick bar: 50% CI, thin bar: 95% CI",
        showarrow=False,
        xanchor="left",
        font={"size": 11, "color": "#334155"},
    )
    fig.update_layout(
        template="simple_white",
        showlegend=False,
        title="Mean restaurant bill with graded 50% and 95% confidence intervals",
        xaxis_title="Mean bill (USD, 50% inner and 95% outer CI)",
        xaxis_range=[8, 32],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 100, "r": 24, "t": 48, "b": 48},
    )
    return fig


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