@* Embeddable AVEVA Galaxy driver config form body. Galaxy connects to a SINGLE mxaccessgw gateway
   (nested Gateway/MxAccess/Repository/Reconnect records) — there is no flat per-device endpoint to split
   out, so the whole connection stays here (GalaxyDeviceForm is informational only). Hosted by the routed
   page + DriverConfigModal. *@
@using System.Text.Json
@using System.Text.Json.Serialization
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers
@using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config

@* mxaccessgw connection *@
<section class="panel rise mt-3" style="animation-delay:.06s">
    <div class="panel-head">mxaccessgw connection</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label">Gateway endpoint</label>
                <InputText @bind-Value="_form.Galaxy.GatewayEndpoint" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono"
                           placeholder="https://localhost:5001" />
                <div class="form-text">gRPC endpoint of the mxaccessgw process.</div>
            </div>
            <div class="col-md-6">
                <label class="form-label">API key secret ref</label>
                <InputText @bind-Value="_form.Galaxy.GatewayApiKeySecretRef" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono"
                           placeholder="env:MX_API_KEY" />
                <div class="form-text">Forms: <code>env:NAME</code>, <code>file:PATH</code>, <code>dev:KEY</code>. Cleartext is accepted but triggers a startup warning.</div>
            </div>
            <div class="col-md-3">
                <div class="form-check form-switch mt-4">
                    <InputCheckbox @bind-Value="_form.Galaxy.GatewayUseTls" @bind-Value:after="EmitAsync" class="form-check-input" id="gwTls" />
                    <label class="form-check-label" for="gwTls">Use TLS</label>
                </div>
            </div>
            <div class="col-md-5">
                <label class="form-label">CA certificate path (optional)</label>
                <InputText @bind-Value="_form.Galaxy.GatewayCaCertificatePath" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono"
                           placeholder="C:\certs\ca.pem" />
            </div>
            <div class="col-md-2">
                <label class="form-label">Connect timeout (s)</label>
                <InputNumber @bind-Value="_form.Galaxy.GatewayConnectTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 10 s.</div>
            </div>
            <div class="col-md-2">
                <label class="form-label">Call timeout (s)</label>
                <InputNumber @bind-Value="_form.Galaxy.GatewayDefaultCallTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 30 s.</div>
            </div>
            <div class="col-md-2">
                <label class="form-label">Stream timeout (s, 0 = unlimited)</label>
                <InputNumber @bind-Value="_form.Galaxy.GatewayStreamTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 0 (lifetime of driver).</div>
            </div>
        </div>
    </div>
</section>

@* MXAccess *@
<section class="panel rise mt-3" style="animation-delay:.08s">
    <div class="panel-head">MXAccess</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Client name</label>
                <InputText @bind-Value="_form.Galaxy.MxClientName" @bind-Value:after="EmitAsync" class="form-control form-control-sm"
                           placeholder="OtOpcUa-Primary" />
                <div class="form-text">Must be unique per OtOpcUa instance — redundancy pairs each get a distinct name.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Publishing interval (ms)</label>
                <InputNumber @bind-Value="_form.Galaxy.MxPublishingIntervalMs" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 1000 ms.</div>
            </div>
            <div class="col-md-2">
                <label class="form-label">Write user ID</label>
                <InputNumber @bind-Value="_form.Galaxy.MxWriteUserId" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">0 = anonymous.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Event pump channel capacity</label>
                <InputNumber @bind-Value="_form.Galaxy.MxEventPumpChannelCapacity" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 50000. Raise if events.dropped appears.</div>
            </div>
        </div>
    </div>
</section>

@* Repository *@
<section class="panel rise mt-3" style="animation-delay:.10s">
    <div class="panel-head">Galaxy repository</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Discover page size</label>
                <InputNumber @bind-Value="_form.Galaxy.RepositoryDiscoverPageSize" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 5000 objects per page.</div>
            </div>
            <div class="col-md-3">
                <div class="form-check form-switch mt-4">
                    <InputCheckbox @bind-Value="_form.Galaxy.RepositoryWatchDeployEvents" @bind-Value:after="EmitAsync" class="form-check-input" id="watchDeploy" />
                    <label class="form-check-label" for="watchDeploy">Watch deploy events</label>
                </div>
                <div class="form-text mt-0">Triggers address-space rebuild on Galaxy re-deploy.</div>
            </div>
        </div>
    </div>
</section>

@* Reconnect *@
<section class="panel rise mt-3" style="animation-delay:.12s">
    <div class="panel-head">Reconnect backoff</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Initial backoff (ms)</label>
                <InputNumber @bind-Value="_form.Galaxy.ReconnectInitialBackoffMs" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 500 ms.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Max backoff (ms)</label>
                <InputNumber @bind-Value="_form.Galaxy.ReconnectMaxBackoffMs" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 30000 ms.</div>
            </div>
            <div class="col-md-3">
                <div class="form-check form-switch mt-4">
                    <InputCheckbox @bind-Value="_form.Galaxy.ReconnectReplayOnSessionLost" @bind-Value:after="EmitAsync" class="form-check-input" id="replayOnLost" />
                    <label class="form-check-label" for="replayOnLost">Replay subscriptions on session lost</label>
                </div>
            </div>
        </div>
    </div>
</section>

@* Diagnostics *@
<section class="panel rise mt-3" style="animation-delay:.14s">
    <div class="panel-head">Diagnostics</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Admin UI probe timeout (seconds)</label>
                <InputNumber @bind-Value="_form.Galaxy.ProbeTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Max 60. Used by Test Connect. Default 30.</div>
            </div>
        </div>
    </div>
</section>

<DriverResilienceSection ResilienceConfig="@ResilienceConfig" ResilienceConfigChanged="OnResilienceChanged" />

@code {
    [Parameter] public string DriverConfigJson { get; set; } = "{}";
    [Parameter] public EventCallback<string> DriverConfigJsonChanged { get; set; }
    [Parameter] public string? ResilienceConfig { get; set; }
    [Parameter] public EventCallback<string?> ResilienceConfigChanged { get; set; }

    private static readonly JsonSerializerOptions _jsonOpts = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true,
        UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
        WriteIndented = false,
        Converters = { new JsonStringEnumConverter() },
    };

    private FormModel _form = new();
    private string? _lastParsed;

    protected override void OnParametersSet()
    {
        if (!string.Equals(_lastParsed, DriverConfigJson, StringComparison.Ordinal))
        {
            var opts = TryDeserialize(DriverConfigJson) ?? CreateDefaultOptions();
            _form = new FormModel { Galaxy = GalaxyFormModel.FromRecord(opts) };
            _lastParsed = DriverConfigJson;
        }
    }

    public string GetConfigJson()
        => JsonSerializer.Serialize(_form.Galaxy.ToRecord(), _jsonOpts);

    private async Task EmitAsync()
    {
        var json = GetConfigJson();
        _lastParsed = json;
        await DriverConfigJsonChanged.InvokeAsync(json);
    }

    private async Task OnResilienceChanged(string? r)
    {
        ResilienceConfig = r;
        await ResilienceConfigChanged.InvokeAsync(r);
    }

    private static GalaxyDriverOptions CreateDefaultOptions() => new(
        Gateway: new GalaxyGatewayOptions("https://localhost:5001", "env:MX_API_KEY"),
        MxAccess: new GalaxyMxAccessOptions("OtOpcUa"),
        Repository: new GalaxyRepositoryOptions(),
        Reconnect: new GalaxyReconnectOptions());

    private static GalaxyDriverOptions? TryDeserialize(string json)
    {
        try { return JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _jsonOpts); }
        catch { return null; }
    }

    public sealed class FormModel
    {
        public GalaxyFormModel Galaxy { get; set; } = new();
    }

    /// <summary>Mutable flat mirror of <see cref="GalaxyDriverOptions"/> and its nested records.</summary>
    public sealed class GalaxyFormModel
    {
        // GalaxyGatewayOptions
        public string GatewayEndpoint { get; set; } = "https://localhost:5001";
        public string GatewayApiKeySecretRef { get; set; } = "env:MX_API_KEY";
        public bool GatewayUseTls { get; set; } = true;
        public string? GatewayCaCertificatePath { get; set; }
        public int GatewayConnectTimeoutSeconds { get; set; } = 10;
        public int GatewayDefaultCallTimeoutSeconds { get; set; } = 30;
        public int GatewayStreamTimeoutSeconds { get; set; } = 0;

        // GalaxyMxAccessOptions
        public string MxClientName { get; set; } = "OtOpcUa";
        public int MxPublishingIntervalMs { get; set; } = 1000;
        public int MxWriteUserId { get; set; } = 0;
        public int MxEventPumpChannelCapacity { get; set; } = 50_000;

        // GalaxyRepositoryOptions
        public int RepositoryDiscoverPageSize { get; set; } = 5000;
        public bool RepositoryWatchDeployEvents { get; set; } = true;

        // GalaxyReconnectOptions
        public int ReconnectInitialBackoffMs { get; set; } = 500;
        public int ReconnectMaxBackoffMs { get; set; } = 30_000;
        public bool ReconnectReplayOnSessionLost { get; set; } = true;

        // GalaxyDriverOptions top-level
        public int ProbeTimeoutSeconds { get; set; } = 30;

        public static GalaxyFormModel FromRecord(GalaxyDriverOptions r)
        {
            var gw   = r.Gateway    ?? new GalaxyGatewayOptions("https://localhost:5001", "env:MX_API_KEY");
            var mx   = r.MxAccess   ?? new GalaxyMxAccessOptions("OtOpcUa");
            var repo = r.Repository ?? new GalaxyRepositoryOptions();
            var rc   = r.Reconnect  ?? new GalaxyReconnectOptions();
            return new()
            {
                GatewayEndpoint = gw.Endpoint,
                GatewayApiKeySecretRef = gw.ApiKeySecretRef,
                GatewayUseTls = gw.UseTls,
                GatewayCaCertificatePath = gw.CaCertificatePath,
                GatewayConnectTimeoutSeconds = gw.ConnectTimeoutSeconds,
                GatewayDefaultCallTimeoutSeconds = gw.DefaultCallTimeoutSeconds,
                GatewayStreamTimeoutSeconds = gw.StreamTimeoutSeconds,
                MxClientName = mx.ClientName,
                MxPublishingIntervalMs = mx.PublishingIntervalMs,
                MxWriteUserId = mx.WriteUserId,
                MxEventPumpChannelCapacity = mx.EventPumpChannelCapacity,
                RepositoryDiscoverPageSize = repo.DiscoverPageSize,
                RepositoryWatchDeployEvents = repo.WatchDeployEvents,
                ReconnectInitialBackoffMs = rc.InitialBackoffMs,
                ReconnectMaxBackoffMs = rc.MaxBackoffMs,
                ReconnectReplayOnSessionLost = rc.ReplayOnSessionLost,
                ProbeTimeoutSeconds = r.ProbeTimeoutSeconds,
            };
        }

        public GalaxyDriverOptions ToRecord() => new(
            Gateway: new GalaxyGatewayOptions(
                Endpoint: GatewayEndpoint,
                ApiKeySecretRef: GatewayApiKeySecretRef,
                UseTls: GatewayUseTls,
                CaCertificatePath: string.IsNullOrWhiteSpace(GatewayCaCertificatePath) ? null : GatewayCaCertificatePath,
                ConnectTimeoutSeconds: GatewayConnectTimeoutSeconds,
                DefaultCallTimeoutSeconds: GatewayDefaultCallTimeoutSeconds,
                StreamTimeoutSeconds: GatewayStreamTimeoutSeconds),
            MxAccess: new GalaxyMxAccessOptions(
                ClientName: MxClientName,
                PublishingIntervalMs: MxPublishingIntervalMs,
                WriteUserId: MxWriteUserId,
                EventPumpChannelCapacity: MxEventPumpChannelCapacity),
            Repository: new GalaxyRepositoryOptions(
                DiscoverPageSize: RepositoryDiscoverPageSize,
                WatchDeployEvents: RepositoryWatchDeployEvents),
            Reconnect: new GalaxyReconnectOptions(
                InitialBackoffMs: ReconnectInitialBackoffMs,
                MaxBackoffMs: ReconnectMaxBackoffMs,
                ReplayOnSessionLost: ReconnectReplayOnSessionLost))
        {
            ProbeTimeoutSeconds = ProbeTimeoutSeconds,
        };
    }
}
