@page "/clusters/{ClusterId}/tags/new"
@page "/clusters/{ClusterId}/tags/{TagId}"
@* Tag CRUD. EquipmentId is required when the chosen driver's namespace is Equipment-kind,
   forbidden when SystemPlatform-kind (decision #110); the form switches between
   "pick equipment" and "FolderPath input" based on namespace kind. *@
@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 tag" : "Edit tag") &middot; <span class="mono">@ClusterId</span></h4>
    <a href="/clusters/@ClusterId/tags" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>

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

@if (!_loaded)
{
    <p>Loading…</p>
}
else if (!IsNew && _existing is null)
{
    <section class="panel notice rise" style="animation-delay:.02s">
        Tag <span class="mono">@TagId</span> was not found.
    </section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="tagEdit">
        <DataAnnotationsValidator />
        <section class="panel rise" style="animation-delay:.02s">
            <div class="panel-head">Identity</div>
            <div style="padding:1rem">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="tagId">TagId</label>
                        <InputText id="tagId" @bind-Value="_form.TagId" disabled="@(!IsNew)"
                                   class="form-control form-control-sm mono"
                                   placeholder="tag-line3-temp-01" />
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="name">Name</label>
                        <InputText id="name" @bind-Value="_form.Name" class="form-control form-control-sm"
                                   placeholder="Temperature setpoint" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="driver">Driver instance</label>
                        <InputSelect id="driver" @bind-Value="_form.DriverInstanceId" class="form-select form-select-sm">
                            <option value="">— pick a driver —</option>
                            @foreach (var d in _drivers)
                            {
                                <option value="@d.DriverInstanceId">@d.DriverInstanceId &mdash; @d.Name</option>
                            }
                        </InputSelect>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="dtype">Data type</label>
                        <InputSelect id="dtype" @bind-Value="_form.DataType" class="form-select form-select-sm">
                            @foreach (var dt in DataTypes)
                            {
                                <option value="@dt">@dt</option>
                            }
                        </InputSelect>
                    </div>
                </div>

                @{ var driverNamespace = ResolveDriverNamespace(_form.DriverInstanceId); }
                @if (driverNamespace?.Kind == NamespaceKind.Equipment)
                {
                    <div class="mb-3">
                        <label class="form-label" for="equipment">Equipment</label>
                        <InputSelect id="equipment" @bind-Value="_form.EquipmentId" class="form-select form-select-sm">
                            <option value="">— pick equipment —</option>
                            @foreach (var e in _equipment.Where(e => e.DriverInstanceId == _form.DriverInstanceId))
                            {
                                <option value="@e.EquipmentId">@e.MachineCode &mdash; @e.Name</option>
                            }
                        </InputSelect>
                    </div>
                }
                else if (driverNamespace?.Kind == NamespaceKind.SystemPlatform)
                {
                    <div class="mb-3">
                        <label class="form-label" for="folder">FolderPath (SystemPlatform namespace)</label>
                        <InputText id="folder" @bind-Value="_form.FolderPath" class="form-control form-control-sm mono"
                                   placeholder="GalaxyArea/Machine_001" />
                        <div class="form-text">Galaxy hierarchy preserved as v1 expressed it — no UNS rule.</div>
                    </div>
                }
                else if (!string.IsNullOrEmpty(_form.DriverInstanceId))
                {
                    <div class="text-muted small mb-3">Pick a driver to see its namespace kind.</div>
                }

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="access">Access level</label>
                        <InputSelect id="access" @bind-Value="_form.AccessLevel" class="form-select form-select-sm">
                            <option value="@TagAccessLevel.Read">Read</option>
                            <option value="@TagAccessLevel.ReadWrite">ReadWrite</option>
                        </InputSelect>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">WriteIdempotent</label>
                        <div class="form-check form-switch">
                            <InputCheckbox @bind-Value="_form.WriteIdempotent" class="form-check-input" />
                            <label class="form-check-label">Safe to retry writes (decision #44–45)</label>
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="pgroup">PollGroupId (optional)</label>
                    <InputText id="pgroup" @bind-Value="_form.PollGroupId" class="form-control form-control-sm mono" />
                </div>
            </div>
        </section>

        <section class="panel rise mt-3" style="animation-delay:.08s">
            <div class="panel-head">Tag config (JSON)</div>
            <div style="padding:1rem">
                <InputTextArea @bind-Value="_form.TagConfig" rows="8"
                               class="form-control form-control-sm mono"
                               placeholder='{ "register": 40001, "scale": 0.1 }' />
                <div class="form-text">Schemaless per driver type — register / address / scaling / byte-order. Validated server-side at deploy.</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/tags" 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 {
    private static readonly string[] DataTypes =
        ["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
         "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid", "ByteString"];

    [Parameter] public string ClusterId { get; set; } = "";
    [Parameter] public string? TagId { get; set; }

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

    private FormModel _form = new();
    private Tag? _existing;
    private List<DriverInstance> _drivers = new();
    private List<Equipment> _equipment = new();
    private Dictionary<string, Namespace> _namespacesByDriverInstance = new();
    private bool _loaded;
    private bool _busy;
    private string? _error;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _drivers = await db.DriverInstances.AsNoTracking()
            .Where(d => d.ClusterId == ClusterId)
            .OrderBy(d => d.DriverInstanceId)
            .ToListAsync();
        var namespaces = await db.Namespaces.AsNoTracking()
            .Where(n => n.ClusterId == ClusterId)
            .ToListAsync();
        var nsById = namespaces.ToDictionary(n => n.NamespaceId);
        _namespacesByDriverInstance = _drivers.ToDictionary(
            d => d.DriverInstanceId,
            d => nsById.TryGetValue(d.NamespaceId, out var ns) ? ns : namespaces.First());
        var driverIds = _drivers.Select(d => d.DriverInstanceId).ToHashSet();
        _equipment = await db.Equipment.AsNoTracking()
            .Where(e => driverIds.Contains(e.DriverInstanceId))
            .OrderBy(e => e.MachineCode)
            .ToListAsync();

        if (!IsNew)
        {
            _existing = await db.Tags.AsNoTracking()
                .FirstOrDefaultAsync(t => t.TagId == TagId);
            if (_existing is not null)
            {
                _form = new FormModel
                {
                    TagId = _existing.TagId,
                    Name = _existing.Name,
                    DriverInstanceId = _existing.DriverInstanceId,
                    EquipmentId = _existing.EquipmentId,
                    FolderPath = _existing.FolderPath,
                    DataType = _existing.DataType,
                    AccessLevel = _existing.AccessLevel,
                    WriteIdempotent = _existing.WriteIdempotent,
                    PollGroupId = _existing.PollGroupId,
                    TagConfig = _existing.TagConfig,
                    RowVersion = _existing.RowVersion,
                };
            }
        }
        else
        {
            _form.DataType = "Float";
            _form.AccessLevel = TagAccessLevel.Read;
            _form.TagConfig = "{}";
        }
        _loaded = true;
    }

    private Namespace? ResolveDriverNamespace(string driverId) =>
        string.IsNullOrEmpty(driverId) ? null
        : _namespacesByDriverInstance.TryGetValue(driverId, out var ns) ? ns : null;

    private async Task SubmitAsync()
    {
        _busy = true; _error = null;
        try
        {
            if (string.IsNullOrEmpty(_form.DriverInstanceId)) { _error = "Pick a driver."; return; }
            var ns = ResolveDriverNamespace(_form.DriverInstanceId);
            if (ns?.Kind == NamespaceKind.Equipment && string.IsNullOrEmpty(_form.EquipmentId))
            { _error = "Driver lives in an Equipment-kind namespace — pick an equipment."; return; }
            if (ns?.Kind == NamespaceKind.SystemPlatform && !string.IsNullOrEmpty(_form.EquipmentId))
            { _error = "Driver lives in a SystemPlatform namespace — EquipmentId must be empty (use FolderPath)."; return; }

            try { using var _ = System.Text.Json.JsonDocument.Parse(_form.TagConfig); }
            catch { _error = "TagConfig is not valid JSON."; return; }

            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                if (await db.Tags.AnyAsync(t => t.TagId == _form.TagId))
                { _error = $"Tag '{_form.TagId}' already exists."; return; }
                db.Tags.Add(new Tag
                {
                    TagId = _form.TagId,
                    DriverInstanceId = _form.DriverInstanceId,
                    EquipmentId = string.IsNullOrEmpty(_form.EquipmentId) ? null : _form.EquipmentId,
                    Name = _form.Name,
                    FolderPath = string.IsNullOrWhiteSpace(_form.FolderPath) ? null : _form.FolderPath,
                    DataType = _form.DataType,
                    AccessLevel = _form.AccessLevel,
                    WriteIdempotent = _form.WriteIdempotent,
                    PollGroupId = string.IsNullOrWhiteSpace(_form.PollGroupId) ? null : _form.PollGroupId,
                    TagConfig = _form.TagConfig,
                });
            }
            else
            {
                var entity = await db.Tags.FirstOrDefaultAsync(t => t.TagId == TagId);
                if (entity is null) { _error = "Row no longer exists."; return; }
                db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
                entity.DriverInstanceId = _form.DriverInstanceId;
                entity.EquipmentId = string.IsNullOrEmpty(_form.EquipmentId) ? null : _form.EquipmentId;
                entity.Name = _form.Name;
                entity.FolderPath = string.IsNullOrWhiteSpace(_form.FolderPath) ? null : _form.FolderPath;
                entity.DataType = _form.DataType;
                entity.AccessLevel = _form.AccessLevel;
                entity.WriteIdempotent = _form.WriteIdempotent;
                entity.PollGroupId = string.IsNullOrWhiteSpace(_form.PollGroupId) ? null : _form.PollGroupId;
                entity.TagConfig = _form.TagConfig;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/tags");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this tag while you were editing."; }
        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.Tags.FirstOrDefaultAsync(t => t.TagId == TagId);
            if (entity is null) { Nav.NavigateTo($"/clusters/{ClusterId}/tags"); return; }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.Tags.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/tags");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this tag while you were viewing it."; }
        catch (Exception ex) { _error = ex.Message; }
        finally { _busy = false; }
    }

    private sealed class FormModel
    {
        [Required, RegularExpression("^[A-Za-z0-9_-]+$")] public string TagId { get; set; } = "";
        [Required] public string Name { get; set; } = "";
        [Required] public string DriverInstanceId { get; set; } = "";
        public string? EquipmentId { get; set; }
        public string? FolderPath { get; set; }
        [Required] public string DataType { get; set; } = "Float";
        public TagAccessLevel AccessLevel { get; set; } = TagAccessLevel.Read;
        public bool WriteIdempotent { get; set; }
        public string? PollGroupId { get; set; }
        [Required] public string TagConfig { get; set; } = "{}";
        public byte[] RowVersion { get; set; } = [];
    }
}
