@using ZB.MOM.WW.OtOpcUa.Admin.Services
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
@inject NamespaceService NsSvc

<div class="d-flex justify-content-between mb-3">
    <h4>Namespaces</h4>
    <button class="btn btn-sm btn-primary" @onclick="() => _showForm = true">Add namespace</button>
</div>

@if (_namespaces is null) { <p>Loading…</p> }
else if (_namespaces.Count == 0) { <p class="text-muted">No namespaces defined in this draft.</p> }
else
{
    <table class="table table-sm">
        <thead><tr><th>NamespaceId</th><th>Kind</th><th>URI</th><th>Enabled</th></tr></thead>
        <tbody>
        @foreach (var n in _namespaces)
        {
            <tr><td><code>@n.NamespaceId</code></td><td>@n.Kind</td><td>@n.NamespaceUri</td><td>@(n.Enabled ? "yes" : "no")</td></tr>
        }
        </tbody>
    </table>
}

@if (_showForm)
{
    <div class="card">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-6"><label class="form-label">NamespaceUri</label><input class="form-control" @bind="_uri"/></div>
                <div class="col-md-6">
                    <label class="form-label">Kind</label>
                    <select class="form-select" @bind="_kind">
                        <option value="@NamespaceKind.Equipment">Equipment</option>
                        <option value="@NamespaceKind.SystemPlatform">SystemPlatform (Galaxy)</option>
                    </select>
                </div>
            </div>
            <div class="mt-3">
                <button class="btn btn-sm btn-primary" @onclick="SaveAsync">Save</button>
                <button class="btn btn-sm btn-secondary ms-2" @onclick="() => _showForm = false">Cancel</button>
            </div>
        </div>
    </div>
}

@code {
    [Parameter] public long GenerationId { get; set; }
    [Parameter] public string ClusterId { get; set; } = string.Empty;
    private List<Namespace>? _namespaces;
    private bool _showForm;
    private string _uri = string.Empty;
    private NamespaceKind _kind = NamespaceKind.Equipment;

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

    private async Task ReloadAsync() =>
        _namespaces = await NsSvc.ListAsync(GenerationId, CancellationToken.None);

    private async Task SaveAsync()
    {
        if (string.IsNullOrWhiteSpace(_uri)) return;
        await NsSvc.AddAsync(GenerationId, ClusterId, _uri, _kind, CancellationToken.None);
        _uri = string.Empty;
        _showForm = false;
        await ReloadAsync();
    }
}
