import numpy as np


import plotly.express as px


import plotly.graph_objects as go


def load_data():
    tips = px.data.tips()
    bills = sorted(round(float(v), 2) for v in tips["tip"].to_numpy())
    return bills


def value_table(data):
    arr = np.array(data, dtype=float)
    return {
        "columns": ["Metric", "Value (USD)"],
        "rows": [
            ["Minimum tip", round(float(arr.min()), 2)],
            ["Median tip", round(float(np.median(arr)), 2)],
            ["90th percentile tip", round(float(np.quantile(arr, 0.9)), 2)],
            ["Maximum tip", round(float(arr.max()), 2)],
        ],
    }


def make_after(data) -> go.Figure:
    arr = np.array(data, dtype=float)
    bw = 0.65
    grid = np.linspace(0.0, 11.0, 180)
    density = np.mean(
        np.exp(-0.5 * ((grid[:, None] - arr[None, :]) / bw) ** 2)
        + np.exp(-0.5 * ((grid[:, None] + arr[None, :]) / bw) ** 2),
        axis=1,
    ) / (bw * np.sqrt(2 * np.pi))
    fig = go.Figure(
        go.Scatter(
            x=grid,
            y=density,
            mode="lines",
            fill="tozeroy",
            name="Reflected tip density",
            line={"color": "#0072B2", "width": 2.5},
            fillcolor="rgba(0, 114, 178, 0.30)",
        )
    )
    fig.add_annotation(
        x=0.25,
        y=0.05,
        text="Bounded at 0 USD (min tip = 1.00 USD)",
        showarrow=False,
        xanchor="left",
        font={"size": 11, "color": "#334155"},
    )
    fig.update_layout(
        template="simple_white",
        xaxis_title="Tip price (USD)",
        yaxis_title="Density",
        xaxis_range=[0, 11],
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        margin={"l": 56, "r": 24, "t": 28, "b": 48},
    )
    return fig


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