@using ZB.MOM.WW.OtOpcUa.Admin.Services
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
@inject GenerationService GenerationSvc
@inject NavigationManager Nav

<h4>Generations</h4>

@if (_generations is null) { <p>Loading…</p> }
else if (_generations.Count == 0) { <p class="text-muted">No generations in this cluster yet.</p> }
else
{
    <table class="table table-sm">
        <thead>
            <tr><th>ID</th><th>Status</th><th>Created</th><th>Published</th><th>PublishedBy</th><th>Notes</th><th></th></tr>
        </thead>
        <tbody>
        @foreach (var g in _generations)
        {
            <tr>
                <td><code>@g.GenerationId</code></td>
                <td>@StatusBadge(g.Status)</td>
                <td><small>@g.CreatedAt.ToString("u") by @g.CreatedBy</small></td>
                <td><small>@(g.PublishedAt?.ToString("u") ?? "-")</small></td>
                <td><small>@g.PublishedBy</small></td>
                <td><small>@g.Notes</small></td>
                <td>
                    @if (g.Status == GenerationStatus.Draft)
                    {
                        <a class="btn btn-sm btn-primary" href="/clusters/@ClusterId/draft/@g.GenerationId">Open</a>
                    }
                    else if (g.Status is GenerationStatus.Published or GenerationStatus.Superseded)
                    {
                        <button class="btn btn-sm btn-outline-warning" @onclick="() => RollbackAsync(g.GenerationId)">Roll back to this</button>
                    }
                </td>
            </tr>
        }
        </tbody>
    </table>
}

@if (_error is not null) { <div class="alert alert-danger">@_error</div> }

@code {
    [Parameter] public string ClusterId { get; set; } = string.Empty;
    private List<ConfigGeneration>? _generations;
    private string? _error;

    protected override async Task OnParametersSetAsync() => await ReloadAsync();

    private async Task ReloadAsync() =>
        _generations = await GenerationSvc.ListRecentAsync(ClusterId, 100, CancellationToken.None);

    private async Task RollbackAsync(long targetId)
    {
        _error = null;
        try
        {
            await GenerationSvc.RollbackAsync(ClusterId, targetId, notes: $"Rollback via Admin UI", CancellationToken.None);
            await ReloadAsync();
        }
        catch (Exception ex) { _error = ex.Message; }
    }

    private static MarkupString StatusBadge(GenerationStatus s) => s switch
    {
        GenerationStatus.Draft      => new MarkupString("<span class='badge bg-info'>Draft</span>"),
        GenerationStatus.Published  => new MarkupString("<span class='badge bg-success'>Published</span>"),
        GenerationStatus.Superseded => new MarkupString("<span class='badge bg-secondary'>Superseded</span>"),
        _                           => new MarkupString($"<span class='badge bg-light text-dark'>{s}</span>"),
    };
}
