@page "/clusters/{ClusterId}/namespaces/new"
@page "/clusters/{ClusterId}/namespaces/{NamespaceId}"
@* Live-edit form pattern — one page handles both create (NamespaceId is null) and update.
   RowVersion is preserved across post-back so EF Core enforces last-write-wins; concurrency
   conflicts surface as a toast and reload the current row. *@
@attribute [Microsoft.AspNetCore.Authorization.Authorize]
@rendermode RenderMode.InteractiveServer
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.EntityFrameworkCore
@using System.ComponentModel.DataAnnotations
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
@inject NavigationManager Nav

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">@(IsNew ? "New namespace" : "Edit namespace") &middot; <span class="mono">@ClusterId</span></h4>
    <a href="/clusters/@ClusterId/namespaces" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>

<ClusterNav ClusterId="@ClusterId" ActiveTab="namespaces" />

@if (!_loaded)
{
    <p>Loading…</p>
}
else if (!IsNew && _existing is null)
{
    <section class="panel notice rise" style="animation-delay:.02s">
        Namespace <span class="mono">@NamespaceId</span> was not found in cluster <span class="mono">@ClusterId</span>.
    </section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="namespaceEdit">
        <DataAnnotationsValidator />
        <section class="panel rise" style="animation-delay:.02s">
            <div class="panel-head">@(IsNew ? "Identity" : $"Edit {_form.NamespaceId}")</div>
            <div style="padding:1rem">
                <div class="mb-3">
                    <label class="form-label" for="nsId">NamespaceId</label>
                    <InputText id="nsId" @bind-Value="_form.NamespaceId" disabled="@(!IsNew)"
                               class="form-control form-control-sm mono"
                               placeholder="LINE3-equipment" />
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="kind">Kind</label>
                        <InputSelect id="kind" @bind-Value="_form.Kind" class="form-select form-select-sm">
                            <option value="@NamespaceKind.Equipment">Equipment (raw signals)</option>
                            <option value="@NamespaceKind.SystemPlatform">System Platform (Galaxy / MXAccess)</option>
                            <option value="@NamespaceKind.Simulated">Simulated (replay — reserved)</option>
                        </InputSelect>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="enabled">Enabled</label>
                        <div class="form-check form-switch">
                            <InputCheckbox id="enabled" @bind-Value="_form.Enabled" class="form-check-input" />
                            <label class="form-check-label" for="enabled">Active in deployments</label>
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="uri">NamespaceUri</label>
                    <InputText id="uri" @bind-Value="_form.NamespaceUri" class="form-control form-control-sm mono"
                               placeholder="urn:zb:warsaw-west:equipment" />
                    <div class="form-text">Must be unique fleet-wide. Clients pin discovery here.</div>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="notes">Notes</label>
                    <InputTextArea id="notes" @bind-Value="_form.Notes" class="form-control form-control-sm" rows="3" />
                </div>
            </div>
        </section>

        @if (!string.IsNullOrWhiteSpace(_error))
        {
            <div class="panel notice mt-3" style="border-color:var(--alert)">@_error</div>
        }

        <div class="mt-3 d-flex gap-2">
            <button type="submit" class="btn btn-primary" disabled="@_busy">
                @if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
                @(IsNew ? "Create" : "Save changes")
            </button>
            <a href="/clusters/@ClusterId/namespaces" class="btn btn-outline-secondary">Cancel</a>
            @if (!IsNew)
            {
                <button type="button" class="btn btn-outline-danger ms-auto" @onclick="DeleteAsync" disabled="@_busy">
                    Delete
                </button>
            }
        </div>
    </EditForm>
}

@code {
    [Parameter] public string ClusterId { get; set; } = "";
    [Parameter] public string? NamespaceId { get; set; }

    private bool IsNew => string.IsNullOrEmpty(NamespaceId);

    private FormModel _form = new();
    private Namespace? _existing;
    private bool _loaded;
    private bool _busy;
    private string? _error;

    protected override async Task OnInitializedAsync()
    {
        if (IsNew)
        {
            _form = new FormModel
            {
                NamespaceId = "",
                Kind = NamespaceKind.Equipment,
                NamespaceUri = "",
                Enabled = true,
            };
        }
        else
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            _existing = await db.Namespaces.AsNoTracking()
                .FirstOrDefaultAsync(n => n.ClusterId == ClusterId && n.NamespaceId == NamespaceId);
            if (_existing is not null)
            {
                _form = new FormModel
                {
                    NamespaceId = _existing.NamespaceId,
                    Kind = _existing.Kind,
                    NamespaceUri = _existing.NamespaceUri,
                    Enabled = _existing.Enabled,
                    Notes = _existing.Notes,
                    RowVersion = _existing.RowVersion,
                };
            }
        }
        _loaded = true;
    }

    private async Task SubmitAsync()
    {
        _busy = true;
        _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                if (await db.Namespaces.AnyAsync(n => n.NamespaceId == _form.NamespaceId))
                {
                    _error = $"Namespace '{_form.NamespaceId}' already exists.";
                    return;
                }
                db.Namespaces.Add(new Namespace
                {
                    NamespaceId = _form.NamespaceId,
                    ClusterId = ClusterId,
                    Kind = _form.Kind,
                    NamespaceUri = _form.NamespaceUri,
                    Enabled = _form.Enabled,
                    Notes = string.IsNullOrWhiteSpace(_form.Notes) ? null : _form.Notes,
                });
            }
            else
            {
                var entity = await db.Namespaces.FirstOrDefaultAsync(
                    n => n.ClusterId == ClusterId && n.NamespaceId == NamespaceId);
                if (entity is null)
                {
                    _error = "Row no longer exists.";
                    return;
                }
                db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
                entity.Kind = _form.Kind;
                entity.NamespaceUri = _form.NamespaceUri;
                entity.Enabled = _form.Enabled;
                entity.Notes = string.IsNullOrWhiteSpace(_form.Notes) ? null : _form.Notes;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/namespaces");
        }
        catch (DbUpdateConcurrencyException)
        {
            _error = "Another user changed this namespace while you were editing. Reload to see the latest values, then re-apply your changes.";
        }
        catch (Exception ex)
        {
            _error = ex.Message;
        }
        finally
        {
            _busy = false;
        }
    }

    private async Task DeleteAsync()
    {
        if (IsNew) return;
        _busy = true;
        _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            var entity = await db.Namespaces.FirstOrDefaultAsync(
                n => n.ClusterId == ClusterId && n.NamespaceId == NamespaceId);
            if (entity is null)
            {
                Nav.NavigateTo($"/clusters/{ClusterId}/namespaces");
                return;
            }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.Namespaces.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/namespaces");
        }
        catch (DbUpdateConcurrencyException)
        {
            _error = "Another user changed this namespace while you were viewing it. Reload before deleting.";
        }
        catch (Exception ex)
        {
            _error = ex.Message;
        }
        finally
        {
            _busy = false;
        }
    }

    private sealed class FormModel
    {
        [Required, RegularExpression("^[A-Za-z0-9_-]+$", ErrorMessage = "Use letters, digits, dash, underscore.")]
        public string NamespaceId { get; set; } = "";
        public NamespaceKind Kind { get; set; } = NamespaceKind.Equipment;
        [Required, RegularExpression("^urn:[A-Za-z0-9_:./-]+$", ErrorMessage = "Use a URN, e.g. urn:zb:warsaw-west:equipment.")]
        public string NamespaceUri { get; set; } = "";
        public bool Enabled { get; set; } = true;
        public string? Notes { get; set; }
        public byte[] RowVersion { get; set; } = [];
    }
}
