@page "/clusters"
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
@inject NavigationManager Nav

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Clusters</h4>
    <a href="/clusters/new" class="btn btn-primary btn-sm">New cluster</a>
</div>

@if (_rows is null)
{
    <p>Loading…</p>
}
else if (_rows.Count == 0)
{
    <section class="panel notice rise" style="animation-delay:.02s">
        No clusters defined yet. Use <strong>New cluster</strong> above to create one.
    </section>
}
else
{
    <section class="panel rise" style="animation-delay:.08s">
        <div class="panel-head">All clusters</div>
        <div class="table-wrap">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Cluster</th>
                        <th>Site</th>
                        <th>Nodes</th>
                        <th>Redundancy</th>
                        <th>Status</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var c in _rows)
                    {
                        <tr style="cursor:pointer" @onclick="() => OpenCluster(c.ClusterId)">
                            <td>
                                <span class="mono">@c.ClusterId</span>
                                <div class="text-muted small">@c.Name</div>
                            </td>
                            <td>@c.Enterprise / @c.Site</td>
                            <td class="num">@c.NodeCount</td>
                            <td>@c.RedundancyMode</td>
                            <td>
                                @if (c.Enabled) { <span class="chip chip-ok">Enabled</span> }
                                else { <span class="chip chip-idle">Disabled</span> }
                            </td>
                            <td class="text-muted small">@c.CreatedAt.ToString("u")</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </section>
}

@code {
    private List<ServerCluster>? _rows;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _rows = await db.ServerClusters.AsNoTracking()
            .OrderBy(c => c.ClusterId)
            .ToListAsync();
    }

    private void OpenCluster(string clusterId) => Nav.NavigateTo($"/clusters/{clusterId}");
}
