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_before(data) -> go.Figure:
    _, old, new = zip(*data, strict=True)
    return _handling_time_figure(
        ["Old workflow", "New workflow"],
        [old, new],
        "Task handling time by workflow",
        "Time (seconds)",
    )


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