@page "/"
@using ZB.MOM.WW.OtOpcUa.Admin.Services
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@inject ClusterService ClusterSvc
@inject GenerationService GenerationSvc
@inject NavigationManager Nav

<h1 class="mb-4">Fleet overview</h1>

@if (_clusters is null)
{
    <p>Loading…</p>
}
else if (_clusters.Count == 0)
{
    <div class="alert alert-info">
        No clusters configured yet. <a href="/clusters/new">Create the first cluster</a>.
    </div>
}
else
{
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="card"><div class="card-body"><h6 class="text-muted">Clusters</h6><div class="fs-2">@_clusters.Count</div></div></div>
        </div>
        <div class="col-md-3">
            <div class="card"><div class="card-body"><h6 class="text-muted">Active drafts</h6><div class="fs-2">@_activeDraftCount</div></div></div>
        </div>
        <div class="col-md-3">
            <div class="card"><div class="card-body"><h6 class="text-muted">Published generations</h6><div class="fs-2">@_publishedCount</div></div></div>
        </div>
        <div class="col-md-3">
            <div class="card"><div class="card-body"><h6 class="text-muted">Disabled clusters</h6><div class="fs-2">@_clusters.Count(c => !c.Enabled)</div></div></div>
        </div>
    </div>

    <h4 class="mt-4 mb-3">Clusters</h4>
    <table class="table table-hover">
        <thead><tr><th>ClusterId</th><th>Name</th><th>Enterprise / Site</th><th>Redundancy</th><th>Enabled</th><th></th></tr></thead>
        <tbody>
        @foreach (var c in _clusters)
        {
            <tr style="cursor: pointer;">
                <td><code>@c.ClusterId</code></td>
                <td>@c.Name</td>
                <td>@c.Enterprise / @c.Site</td>
                <td>@c.RedundancyMode</td>
                <td>@(c.Enabled ? "Yes" : "No")</td>
                <td><a href="/clusters/@c.ClusterId" class="btn btn-sm btn-outline-primary">Open</a></td>
            </tr>
        }
        </tbody>
    </table>
}

@code {
    private List<ServerCluster>? _clusters;
    private int _activeDraftCount;
    private int _publishedCount;

    protected override async Task OnInitializedAsync()
    {
        _clusters = await ClusterSvc.ListAsync(CancellationToken.None);

        foreach (var c in _clusters)
        {
            var gens = await GenerationSvc.ListRecentAsync(c.ClusterId, 50, CancellationToken.None);
            _activeDraftCount += gens.Count(g => g.Status.ToString() == "Draft");
            _publishedCount += gens.Count(g => g.Status.ToString() == "Published");
        }
    }
}
