@page "/virtual-tags/new"
@page "/virtual-tags/{VirtualTagId}"
@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
@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 virtual tag" : "Edit virtual tag")</h4>
    <a href="/virtual-tags" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>

@if (!_loaded)
{
    <p>Loading…</p>
}
else if (!IsNew && _existing is null)
{
    <section class="panel notice rise"><span class="mono">@VirtualTagId</span> not found.</section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="vtagEdit">
        <DataAnnotationsValidator />
        <section class="panel rise">
            <div class="panel-head">Identity</div>
            <div style="padding:1rem">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">VirtualTagId</label>
                        <InputText @bind-Value="_form.VirtualTagId" disabled="@(!IsNew)" class="form-control form-control-sm mono" />
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Name</label>
                        <InputText @bind-Value="_form.Name" class="form-control form-control-sm" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Equipment</label>
                        <InputSelect @bind-Value="_form.EquipmentId" class="form-select form-select-sm">
                            <option value="">— pick equipment —</option>
                            @foreach (var e in _equipment) { <option value="@e.EquipmentId">@e.MachineCode &mdash; @e.Name</option> }
                        </InputSelect>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">DataType</label>
                        <InputText @bind-Value="_form.DataType" class="form-control form-control-sm mono" placeholder="Double" />
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Script</label>
                        <InputSelect @bind-Value="_form.ScriptId" class="form-select form-select-sm">
                            <option value="">— pick script —</option>
                            @foreach (var s in _scripts) { <option value="@s.ScriptId">@s.Name (@s.Language)</option> }
                        </InputSelect>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Change-triggered</label>
                        <div class="form-check form-switch">
                            <InputCheckbox @bind-Value="_form.ChangeTriggered" class="form-check-input" />
                            <label class="form-check-label">Re-evaluate on dependency change</label>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">TimerIntervalMs (optional)</label>
                        <InputNumber @bind-Value="_form.TimerIntervalMs" class="form-control form-control-sm" />
                        <div class="form-text">Periodic re-evaluation. Null = change-trigger only.</div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Historize</label>
                        <div class="form-check form-switch">
                            <InputCheckbox @bind-Value="_form.Historize" class="form-check-input" />
                            <label class="form-check-label">Send to Wonderware historian</label>
                        </div>
                    </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 this virtual tag in deployments</label>
                    </div>
                </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">@(IsNew ? "Create" : "Save changes")</button>
            <a href="/virtual-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 {
    [Parameter] public string? VirtualTagId { get; set; }
    private bool IsNew => string.IsNullOrEmpty(VirtualTagId);

    private FormModel _form = new();
    private VirtualTag? _existing;
    private List<Equipment> _equipment = new();
    private List<Script> _scripts = new();
    private bool _loaded;
    private bool _busy;
    private string? _error;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _equipment = await db.Equipment.AsNoTracking().OrderBy(e => e.MachineCode).ToListAsync();
        _scripts = await db.Scripts.AsNoTracking().OrderBy(s => s.Name).ToListAsync();
        if (!IsNew)
        {
            _existing = await db.VirtualTags.AsNoTracking().FirstOrDefaultAsync(v => v.VirtualTagId == VirtualTagId);
            if (_existing is not null)
            {
                _form = new FormModel
                {
                    VirtualTagId = _existing.VirtualTagId,
                    Name = _existing.Name,
                    EquipmentId = _existing.EquipmentId,
                    DataType = _existing.DataType,
                    ScriptId = _existing.ScriptId,
                    ChangeTriggered = _existing.ChangeTriggered,
                    TimerIntervalMs = _existing.TimerIntervalMs,
                    Historize = _existing.Historize,
                    Enabled = _existing.Enabled,
                    RowVersion = _existing.RowVersion,
                };
            }
        }
        else
        {
            _form.DataType = "Double";
            _form.ChangeTriggered = true;
        }
        _loaded = true;
    }

    private async Task SubmitAsync()
    {
        _busy = true; _error = null;
        try
        {
            if (string.IsNullOrEmpty(_form.EquipmentId)) { _error = "Pick equipment."; return; }
            if (string.IsNullOrEmpty(_form.ScriptId)) { _error = "Pick a script."; return; }
            if (!_form.ChangeTriggered && _form.TimerIntervalMs is null)
            { _error = "Pick at least one trigger — change or timer."; return; }

            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                if (await db.VirtualTags.AnyAsync(v => v.VirtualTagId == _form.VirtualTagId))
                { _error = $"VirtualTag '{_form.VirtualTagId}' already exists."; return; }
                db.VirtualTags.Add(new VirtualTag
                {
                    VirtualTagId = _form.VirtualTagId,
                    EquipmentId = _form.EquipmentId,
                    Name = _form.Name,
                    DataType = _form.DataType,
                    ScriptId = _form.ScriptId,
                    ChangeTriggered = _form.ChangeTriggered,
                    TimerIntervalMs = _form.TimerIntervalMs,
                    Historize = _form.Historize,
                    Enabled = _form.Enabled,
                });
            }
            else
            {
                var entity = await db.VirtualTags.FirstOrDefaultAsync(v => v.VirtualTagId == VirtualTagId);
                if (entity is null) { _error = "Row no longer exists."; return; }
                db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
                entity.EquipmentId = _form.EquipmentId;
                entity.Name = _form.Name;
                entity.DataType = _form.DataType;
                entity.ScriptId = _form.ScriptId;
                entity.ChangeTriggered = _form.ChangeTriggered;
                entity.TimerIntervalMs = _form.TimerIntervalMs;
                entity.Historize = _form.Historize;
                entity.Enabled = _form.Enabled;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo("/virtual-tags");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this virtual 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.VirtualTags.FirstOrDefaultAsync(v => v.VirtualTagId == VirtualTagId);
            if (entity is null) { Nav.NavigateTo("/virtual-tags"); return; }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.VirtualTags.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo("/virtual-tags");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this virtual 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 VirtualTagId { get; set; } = "";
        [Required] public string Name { get; set; } = "";
        [Required] public string EquipmentId { get; set; } = "";
        [Required] public string DataType { get; set; } = "Double";
        [Required] public string ScriptId { get; set; } = "";
        public bool ChangeTriggered { get; set; } = true;
        public int? TimerIntervalMs { get; set; }
        public bool Historize { get; set; }
        public bool Enabled { get; set; } = true;
        public byte[] RowVersion { get; set; } = [];
    }
}
