from statistics import mean, stdev


import plotly.graph_objects as go


def load_data():
    """Return paired handling times in seconds by employee."""
    return [
        ("A", 50, 46),
        ("B", 62, 59),
        ("C", 44, 38),
        ("D", 71, 66),
        ("E", 56, 54),
    ]


def value_table(data):
    return {
        "columns": [
            "Employee",
            "Old workflow (seconds)",
            "New workflow (seconds)",
            "Seconds saved",
        ],
        "rows": [[name, old, new, old - new] for name, old, new in data],
    }


def _handling_time_figure(labels, samples, title, axis_title):
    centers = [mean(sample) for sample in samples]
    margins = [2.776 * stdev(sample) / len(sample) ** 0.5 for sample in samples]
    fig = go.Figure(
        go.Scatter(
            x=centers,
            y=labels,
            mode="markers",
            marker={"color": "#22628a", "size": 10},
            error_x={"array": margins, "color": "#22628a", "width": 5},
            customdata=margins,
            hovertemplate="%{y}<br>%{x:.1f} s ± %{customdata:.1f} s<extra></extra>",
        )
    )
    fig.update_layout(
        template="simple_white",
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "color": "#1f2937"},
        title={"text": title, "subtitle": {"text": "Means with 95% confidence intervals"}},
        xaxis_title=axis_title,
        yaxis_autorange="reversed",
        margin={"l": 120, "r": 24, "t": 78, "b": 60},
    )
    return fig


def make_after(data) -> go.Figure:
    names = [name for name, _, _ in data]
    seconds_saved = [old - new for _, old, new in data]
    fig = _handling_time_figure(
        ["Paired mean (95% CI)"],
        [seconds_saved],
        "Paired time savings",
        "Seconds saved with the new workflow",
    )
    fig.add_trace(
        go.Scatter(
            x=seconds_saved,
            y=[f"Employee {name}" for name in names],
            mode="markers",
            marker={"color": "#64748b", "size": 8},
            hovertemplate="%{y}<br>%{x} s saved<extra></extra>",
        )
    )
    fig.update_layout(showlegend=False)
    fig.update_xaxes(range=[-0.5, 7])
    fig.add_vline(x=0, line_color="#9ca3af", line_dash="dot")
    return fig


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