@page "/clusters/{ClusterId}/edit"
@* Edit page for an existing ServerCluster. The /clusters/new route lives in NewCluster.razor;
   this page handles only the update case so the form can disable ClusterId (immutable). *@
@attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)]
@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
@inject AuthenticationStateProvider AuthState

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

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

@if (!_loaded)
{
    <p>Loading…</p>
}
else if (_existing is null)
{
    <section class="panel notice rise" style="animation-delay:.02s">
        Cluster <span class="mono">@ClusterId</span> was not found.
    </section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="clusterEdit">
        <DataAnnotationsValidator />
        <section class="panel rise" style="animation-delay:.02s">
            <div class="panel-head">Identity</div>
            <div style="padding:1rem">
                <div class="mb-3">
                    <label class="form-label">ClusterId</label>
                    <input class="form-control form-control-sm mono" value="@ClusterId" disabled />
                    <div class="form-text">Immutable after creation. Operator-visible everywhere; renames would invalidate every downstream reference.</div>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="name">Name</label>
                    <InputText id="name" @bind-Value="_form.Name" class="form-control form-control-sm" />
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="enterprise">Enterprise</label>
                        <InputText id="enterprise" @bind-Value="_form.Enterprise" class="form-control form-control-sm" />
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="site">Site</label>
                        <InputText id="site" @bind-Value="_form.Site" class="form-control form-control-sm" />
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Enabled</label>
                    <div class="form-check form-switch">
                        <InputCheckbox @bind-Value="_form.Enabled" class="form-check-input" />
                        <label class="form-check-label">Spawn drivers + serve endpoints in deployments</label>
                    </div>
                </div>
            </div>
        </section>

        <section class="panel rise mt-3" style="animation-delay:.08s">
            <div class="panel-head">Topology</div>
            <div style="padding:1rem">
                <div class="mb-3">
                    <label class="form-label" for="redundancy">Redundancy mode</label>
                    <InputSelect id="redundancy" @bind-Value="_form.RedundancyMode" class="form-select form-select-sm">
                        <option value="@RedundancyMode.None">None (1 node)</option>
                        <option value="@RedundancyMode.Warm">Warm (2 nodes)</option>
                        <option value="@RedundancyMode.Hot">Hot (2 nodes)</option>
                    </InputSelect>
                </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> }
                Save changes
            </button>
            <a href="/clusters/@ClusterId" class="btn btn-outline-secondary">Cancel</a>
            <button type="button" class="btn btn-outline-danger ms-auto" @onclick="DeleteAsync" disabled="@_busy">
                Delete cluster
            </button>
        </div>
    </EditForm>
}

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

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

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _existing = await db.ServerClusters.AsNoTracking()
            .FirstOrDefaultAsync(c => c.ClusterId == ClusterId);
        if (_existing is not null)
        {
            _form = new FormModel
            {
                Name = _existing.Name,
                Enterprise = _existing.Enterprise,
                Site = _existing.Site,
                RedundancyMode = _existing.RedundancyMode,
                Enabled = _existing.Enabled,
                Notes = _existing.Notes,
            };
        }
        _loaded = true;
    }

    private async Task SubmitAsync()
    {
        _busy = true;
        _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            var entity = await db.ServerClusters.FirstOrDefaultAsync(c => c.ClusterId == ClusterId);
            if (entity is null) { _error = "Cluster no longer exists."; return; }

            var auth = await AuthState.GetAuthenticationStateAsync();
            entity.Name = _form.Name;
            entity.Enterprise = _form.Enterprise;
            entity.Site = _form.Site;
            entity.RedundancyMode = _form.RedundancyMode;
            entity.NodeCount = _form.RedundancyMode == RedundancyMode.None ? (byte)1 : (byte)2;
            entity.Enabled = _form.Enabled;
            entity.Notes = string.IsNullOrWhiteSpace(_form.Notes) ? null : _form.Notes;
            entity.ModifiedAt = DateTime.UtcNow;
            entity.ModifiedBy = auth.User.Identity?.Name ?? "(anonymous)";

            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}");
        }
        catch (Exception ex)
        {
            _error = ex.Message;
        }
        finally
        {
            _busy = false;
        }
    }

    private async Task DeleteAsync()
    {
        _busy = true;
        _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            var entity = await db.ServerClusters.FirstOrDefaultAsync(c => c.ClusterId == ClusterId);
            if (entity is null) { Nav.NavigateTo("/clusters"); return; }
            db.ServerClusters.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo("/clusters");
        }
        catch (Exception ex)
        {
            _error = $"Delete failed: {ex.Message}. Likely because nodes, namespaces, drivers, or other rows still reference this cluster — remove them first.";
        }
        finally
        {
            _busy = false;
        }
    }

    private sealed class FormModel
    {
        [Required] public string Name { get; set; } = "";
        [Required] public string Enterprise { get; set; } = "";
        [Required] public string Site { get; set; } = "";
        public RedundancyMode RedundancyMode { get; set; } = RedundancyMode.None;
        public bool Enabled { get; set; } = true;
        public string? Notes { get; set; }
    }
}
