@page "/clusters/new"
@attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)]
@rendermode RenderMode.InteractiveServer
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.EntityFrameworkCore
@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">New cluster</h4>
    <a href="/clusters" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>

<EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="newCluster">
    <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" for="clusterId">Cluster ID</label>
                <InputText id="clusterId" @bind-Value="_form.ClusterId" class="form-control form-control-sm mono"
                           placeholder="LINE3-OPCUA" />
            </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"
                               placeholder="zb" />
                </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"
                               placeholder="warsaw-west" />
                </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, non-transparent)</option>
                    <option value="@RedundancyMode.Hot">Hot (2 nodes, non-transparent)</option>
                </InputSelect>
                <div class="form-text">NodeCount is implied — 1 for None, 2 for Warm/Hot.</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">@_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> }
            Create cluster
        </button>
        <a href="/clusters" class="btn btn-outline-secondary">Cancel</a>
    </div>
</EditForm>

@code {
    private FormModel _form = new();
    private string? _error;
    private bool _busy;

    private async Task SubmitAsync()
    {
        _busy = true;
        _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            if (await db.ServerClusters.AnyAsync(c => c.ClusterId == _form.ClusterId))
            {
                _error = $"Cluster '{_form.ClusterId}' already exists.";
                return;
            }

            var auth = await AuthState.GetAuthenticationStateAsync();
            var createdBy = auth.User.Identity?.Name ?? "(anonymous)";

            var entity = new ServerCluster
            {
                ClusterId = _form.ClusterId,
                Name = _form.Name,
                Enterprise = _form.Enterprise,
                Site = _form.Site,
                RedundancyMode = _form.RedundancyMode,
                NodeCount = _form.RedundancyMode == RedundancyMode.None ? (byte)1 : (byte)2,
                Notes = string.IsNullOrWhiteSpace(_form.Notes) ? null : _form.Notes,
                Enabled = true,
                CreatedAt = DateTime.UtcNow,
                CreatedBy = createdBy,
            };
            db.ServerClusters.Add(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{entity.ClusterId}");
        }
        catch (Exception ex)
        {
            _error = ex.Message;
        }
        finally
        {
            _busy = false;
        }
    }

    private sealed class FormModel
    {
        [System.ComponentModel.DataAnnotations.Required, System.ComponentModel.DataAnnotations.RegularExpression("^[A-Z0-9_-]+$", ErrorMessage = "Use uppercase letters, digits, dash, underscore.")]
        public string ClusterId { get; set; } = "";
        [System.ComponentModel.DataAnnotations.Required]
        public string Name { get; set; } = "";
        [System.ComponentModel.DataAnnotations.Required]
        public string Enterprise { get; set; } = "zb";
        [System.ComponentModel.DataAnnotations.Required]
        public string Site { get; set; } = "";
        public RedundancyMode RedundancyMode { get; set; } = RedundancyMode.None;
        public string? Notes { get; set; }
    }
}
