@* Embeddable OPC UA Client driver config form body. The single connection Endpoint URL moved to
   OpcUaClientDeviceForm (Device.DeviceConfig) in v3; the EndpointUrls FAILOVER LIST stays here (it is a
   driver-level policy). Hosted by the routed page + DriverConfigModal. *@
@using System.Text.Json
@using System.Text.Json.Nodes
@using System.Text.Json.Serialization
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers
@using ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient

@* Endpoint (single Endpoint URL moved to the device form) *@
<section class="panel rise mt-3" style="animation-delay:.06s">
    <div class="panel-head">Endpoint</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Browse root NodeId (blank = ObjectsFolder)</label>
                <InputText @bind-Value="_form.OpcUa.BrowseRoot" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono" placeholder="i=85" />
                <div class="form-text">Restrict mirroring to a sub-tree.</div>
            </div>
            <div class="col-md-4">
                <label class="form-label">Application URI</label>
                <InputText @bind-Value="_form.OpcUa.ApplicationUri" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono" />
            </div>
            <div class="col-md-4">
                <label class="form-label">Session name</label>
                <InputText @bind-Value="_form.OpcUa.SessionName" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
            </div>
            <div class="col-md-4">
                <div class="form-check form-switch mt-4">
                    <InputCheckbox @bind-Value="_form.OpcUa.AutoAcceptCertificates" @bind-Value:after="EmitAsync" class="form-check-input" id="autoAcceptCerts" />
                    <label class="form-check-label" for="autoAcceptCerts">Auto-accept certificates <span class="badge bg-warning text-dark">Dev only</span></label>
                </div>
            </div>
        </div>
        <div class="row g-3 mt-1">
            <div class="col-md-3">
                <label class="form-label">Per-endpoint connect timeout (s)</label>
                <InputNumber @bind-Value="_form.OpcUa.PerEndpointConnectTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 3 s — failover sweep budget.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Operation timeout (s)</label>
                <InputNumber @bind-Value="_form.OpcUa.TimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 10 s — steady-state reads/writes.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Session timeout (s)</label>
                <InputNumber @bind-Value="_form.OpcUa.SessionTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 120 s.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Keep-alive interval (s)</label>
                <InputNumber @bind-Value="_form.OpcUa.KeepAliveIntervalSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 5 s.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Reconnect period (s)</label>
                <InputNumber @bind-Value="_form.OpcUa.ReconnectPeriodSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Initial delay after session drop. Default 5 s.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Max discovered nodes</label>
                <InputNumber @bind-Value="_form.OpcUa.MaxDiscoveredNodes" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 10000.</div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Max browse depth</label>
                <InputNumber @bind-Value="_form.OpcUa.MaxBrowseDepth" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Default 10.</div>
            </div>
        </div>
        <div class="row g-3 mt-1">
            <div class="col-12">
                <CollectionEditor TRow="EndpointUrlRow" Items="_endpoints" ItemsChanged="EmitAsync"
                                  Title="Endpoint URLs" ItemNoun="endpoint" AnimationDelay=".07s"
                                  NewRow="@(() => new EndpointUrlRow())" Clone="@(r => r.Clone())"
                                  Validate="EndpointUrlRow.ValidateRow">
                    <HeaderTemplate>
                        <tr><th>Endpoint URL (failover list — first reachable wins)</th><th></th></tr>
                    </HeaderTemplate>
                    <RowTemplate Context="e">
                        <td class="mono">@e.Url</td>
                    </RowTemplate>
                    <EditTemplate Context="e">
                        <label class="form-label">Endpoint URL</label>
                        <input class="form-control form-control-sm mono" @bind="e.Url"
                               placeholder="opc.tcp://plc.internal:4840" />
                        <div class="form-text">Failover list. The per-device Endpoint URL (on the device) is used only when this list is empty.</div>
                    </EditTemplate>
                </CollectionEditor>
            </div>
        </div>
    </div>
</section>

@* Security *@
<section class="panel rise mt-3" style="animation-delay:.08s">
    <div class="panel-head">Security</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Security mode</label>
                <InputSelect @bind-Value="_form.OpcUa.SecurityMode" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
                    @foreach (var e in Enum.GetValues<OpcUaSecurityMode>())
                    {
                        <option value="@e">@e</option>
                    }
                </InputSelect>
            </div>
            <div class="col-md-4">
                <label class="form-label">Security policy</label>
                <InputSelect @bind-Value="_form.OpcUa.SecurityPolicy" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
                    @foreach (var e in Enum.GetValues<OpcUaSecurityPolicy>())
                    {
                        <option value="@e">@e</option>
                    }
                </InputSelect>
            </div>
        </div>
    </div>
</section>

@* Authentication *@
<section class="panel rise mt-3" style="animation-delay:.10s">
    <div class="panel-head">Authentication</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Auth type</label>
                <InputSelect @bind-Value="_form.OpcUa.AuthType" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
                    @foreach (var e in Enum.GetValues<OpcUaAuthType>())
                    {
                        <option value="@e">@e</option>
                    }
                </InputSelect>
            </div>
            @if (_form.OpcUa.AuthType == OpcUaAuthType.Username)
            {
                <div class="col-md-4">
                    <label class="form-label">Username</label>
                    <InputText @bind-Value="_form.OpcUa.Username" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                </div>
                <div class="col-md-4">
                    <label class="form-label">Password</label>
                    <InputText @bind-Value="_form.OpcUa.Password" @bind-Value:after="EmitAsync" type="password" class="form-control form-control-sm" autocomplete="new-password" />
                </div>
            }
            @if (_form.OpcUa.AuthType == OpcUaAuthType.Certificate)
            {
                <div class="col-md-6">
                    <label class="form-label">User certificate path (PFX/PEM)</label>
                    <InputText @bind-Value="_form.OpcUa.UserCertificatePath" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono"
                               placeholder="C:\certs\user.pfx" />
                </div>
                <div class="col-md-4">
                    <label class="form-label">Certificate password (if PFX-locked)</label>
                    <InputText @bind-Value="_form.OpcUa.UserCertificatePassword" @bind-Value:after="EmitAsync" type="password" class="form-control form-control-sm" autocomplete="new-password" />
                </div>
            }
        </div>
    </div>
</section>

@* Namespace mapping *@
<section class="panel rise mt-3" style="animation-delay:.12s">
    <div class="panel-head">Namespace mapping</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Target namespace kind</label>
                <InputSelect @bind-Value="_form.OpcUa.TargetNamespaceKind" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
                    @foreach (var e in Enum.GetValues<OpcUaTargetNamespaceKind>())
                    {
                        <option value="@e">@e</option>
                    }
                </InputSelect>
                <div class="form-text">Equipment = raw data re-mapped to UNS. SystemPlatform = processed data; hierarchy preserved as-is.</div>
            </div>
            <div class="col-12">
                <label class="form-label">UNS mapping table (read-only — edit via raw JSON import)</label>
                <pre class="form-control form-control-sm mono" style="min-height:3rem;overflow:auto;white-space:pre-wrap;">@_unsMappingTableJson</pre>
                <div class="form-text">Keys = remote browse-path prefixes; values = UNS Area/Line/Name paths. Required when TargetNamespaceKind = Equipment.</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.OpcUa.ProbeTimeoutSeconds" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
                <div class="form-text">Max 60. Used by Test Connect. Default 15.</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,
        UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
        WriteIndented = false,
        Converters = { new JsonStringEnumConverter() },
    };

    private FormModel _form = new();
    private List<EndpointUrlRow> _endpoints = [];
    private string _unsMappingTableJson = "{}";
    private string? _lastParsed;

    protected override void OnParametersSet()
    {
        if (!string.Equals(_lastParsed, DriverConfigJson, StringComparison.Ordinal))
        {
            var opts = TryDeserialize(DriverConfigJson) ?? new OpcUaClientDriverOptions();
            _form = new FormModel { OpcUa = OpcUaClientFormModel.FromRecord(opts) };
            _endpoints = opts.EndpointUrls.Select(EndpointUrlRow.FromUrl).ToList();
            _unsMappingTableJson = JsonSerializer.Serialize(opts.UnsMappingTable, _jsonOpts);
            _lastParsed = DriverConfigJson;
        }
    }

    public string GetConfigJson()
    {
        // v3 (reviewer H1): the convenience scalar endpoint lives on the Device (DeviceConfig). Strip the
        // scalar "endpointUrl" so the device is its sole source; the "endpointUrls" failover list stays
        // here (it is a driver-level policy and wins over the scalar at runtime when populated).
        var node = JsonSerializer.SerializeToNode(
            _form.OpcUa.ToRecord(_endpoints.Select(r => r.ToUrl()).ToList()), _jsonOpts)!.AsObject();
        node.Remove("endpointUrl");
        return node.ToJsonString(_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 OpcUaClientDriverOptions? TryDeserialize(string json)
    {
        try { return JsonSerializer.Deserialize<OpcUaClientDriverOptions>(json, _jsonOpts); }
        catch { return null; }
    }

    public sealed class FormModel
    {
        public OpcUaClientFormModel OpcUa { get; set; } = new();
    }

    /// <summary>Mutable VM for a single failover endpoint URL row.</summary>
    public sealed class EndpointUrlRow
    {
        public string Url { get; set; } = "";
        public EndpointUrlRow Clone() => (EndpointUrlRow)MemberwiseClone();
        public static EndpointUrlRow FromUrl(string u) => new() { Url = u };
        public string ToUrl() => Url.Trim();

        public static string? ValidateRow(EndpointUrlRow row, IReadOnlyList<EndpointUrlRow> all, int? editIndex)
        {
            if (string.IsNullOrWhiteSpace(row.Url)) return "URL is required.";
            if (!row.Url.Trim().StartsWith("opc.tcp://", StringComparison.OrdinalIgnoreCase))
                return "Endpoint URL must start with opc.tcp://";
            for (var i = 0; i < all.Count; i++)
                if (i != editIndex && string.Equals(all[i].Url.Trim(), row.Url.Trim(), StringComparison.OrdinalIgnoreCase))
                    return $"Duplicate endpoint '{row.Url}'.";
            return null;
        }
    }

    /// <summary>Mutable mirror of <see cref="OpcUaClientDriverOptions"/> (int wrappers for TimeSpans).
    /// EndpointUrl (single) has NO UI — the device form authors it; kept at default so ToRecord is valid.</summary>
    public sealed class OpcUaClientFormModel
    {
        // Connection (EndpointUrl authored on the device — no UI here)
        public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
        public string? BrowseRoot { get; set; }
        public string ApplicationUri { get; set; } = "urn:localhost:OtOpcUa:GatewayClient";
        public string SessionName { get; set; } = "OtOpcUa-Gateway";
        public bool AutoAcceptCertificates { get; set; } = false;
        public int PerEndpointConnectTimeoutSeconds { get; set; } = 3;
        public int TimeoutSeconds { get; set; } = 10;
        public int SessionTimeoutSeconds { get; set; } = 120;
        public int KeepAliveIntervalSeconds { get; set; } = 5;
        public int ReconnectPeriodSeconds { get; set; } = 5;
        public int MaxDiscoveredNodes { get; set; } = 10_000;
        public int MaxBrowseDepth { get; set; } = 10;

        public OpcUaSecurityMode SecurityMode { get; set; } = OpcUaSecurityMode.None;
        public OpcUaSecurityPolicy SecurityPolicy { get; set; } = OpcUaSecurityPolicy.None;

        public OpcUaAuthType AuthType { get; set; } = OpcUaAuthType.Anonymous;
        public string? Username { get; set; }
        public string? Password { get; set; }
        public string? UserCertificatePath { get; set; }
        public string? UserCertificatePassword { get; set; }

        public OpcUaTargetNamespaceKind TargetNamespaceKind { get; set; } = OpcUaTargetNamespaceKind.Equipment;

        public int ProbeTimeoutSeconds { get; set; } = 15;

        internal IReadOnlyDictionary<string, string> _unsMappingTable = new Dictionary<string, string>();

        public static OpcUaClientFormModel FromRecord(OpcUaClientDriverOptions r) => new()
        {
            EndpointUrl = r.EndpointUrl,
            BrowseRoot = r.BrowseRoot,
            ApplicationUri = r.ApplicationUri,
            SessionName = r.SessionName,
            AutoAcceptCertificates = r.AutoAcceptCertificates,
            PerEndpointConnectTimeoutSeconds = (int)r.PerEndpointConnectTimeout.TotalSeconds,
            TimeoutSeconds = (int)r.Timeout.TotalSeconds,
            SessionTimeoutSeconds = (int)r.SessionTimeout.TotalSeconds,
            KeepAliveIntervalSeconds = (int)r.KeepAliveInterval.TotalSeconds,
            ReconnectPeriodSeconds = (int)r.ReconnectPeriod.TotalSeconds,
            MaxDiscoveredNodes = r.MaxDiscoveredNodes,
            MaxBrowseDepth = r.MaxBrowseDepth,
            SecurityMode = r.SecurityMode,
            SecurityPolicy = r.SecurityPolicy,
            AuthType = r.AuthType,
            Username = r.Username,
            Password = r.Password,
            UserCertificatePath = r.UserCertificatePath,
            UserCertificatePassword = r.UserCertificatePassword,
            TargetNamespaceKind = r.TargetNamespaceKind,
            ProbeTimeoutSeconds = r.ProbeTimeoutSeconds,
            _unsMappingTable = r.UnsMappingTable,
        };

        public OpcUaClientDriverOptions ToRecord(IReadOnlyList<string> endpointUrls) => new()
        {
            EndpointUrl = EndpointUrl,
            EndpointUrls = endpointUrls,
            BrowseRoot = string.IsNullOrWhiteSpace(BrowseRoot) ? null : BrowseRoot,
            ApplicationUri = ApplicationUri,
            SessionName = SessionName,
            AutoAcceptCertificates = AutoAcceptCertificates,
            PerEndpointConnectTimeout = TimeSpan.FromSeconds(PerEndpointConnectTimeoutSeconds),
            Timeout = TimeSpan.FromSeconds(TimeoutSeconds),
            SessionTimeout = TimeSpan.FromSeconds(SessionTimeoutSeconds),
            KeepAliveInterval = TimeSpan.FromSeconds(KeepAliveIntervalSeconds),
            ReconnectPeriod = TimeSpan.FromSeconds(ReconnectPeriodSeconds),
            MaxDiscoveredNodes = MaxDiscoveredNodes,
            MaxBrowseDepth = MaxBrowseDepth,
            SecurityMode = SecurityMode,
            SecurityPolicy = SecurityPolicy,
            AuthType = AuthType,
            Username = string.IsNullOrWhiteSpace(Username) ? null : Username,
            Password = string.IsNullOrWhiteSpace(Password) ? null : Password,
            UserCertificatePath = string.IsNullOrWhiteSpace(UserCertificatePath) ? null : UserCertificatePath,
            UserCertificatePassword = string.IsNullOrWhiteSpace(UserCertificatePassword) ? null : UserCertificatePassword,
            TargetNamespaceKind = TargetNamespaceKind,
            UnsMappingTable = _unsMappingTable,
            ProbeTimeoutSeconds = ProbeTimeoutSeconds,
        };
    }
}
