@page "/scripted-alarms/new"
@page "/scripted-alarms/{ScriptedAlarmId}"
@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 scripted alarm" : "Edit scripted alarm")</h4>
    <a href="/scripted-alarms" 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">@ScriptedAlarmId</span> not found.</section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="scriptedAlarmEdit">
        <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">ScriptedAlarmId</label>
                        <InputText @bind-Value="_form.ScriptedAlarmId" 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">AlarmType</label>
                        <InputSelect @bind-Value="_form.AlarmType" class="form-select form-select-sm">
                            <option value="LimitAlarm">LimitAlarm</option>
                            <option value="DiscreteAlarm">DiscreteAlarm</option>
                            <option value="OffNormalAlarm">OffNormalAlarm</option>
                            <option value="AlarmCondition">AlarmCondition</option>
                        </InputSelect>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Severity (1-1000)</label>
                        <InputNumber @bind-Value="_form.Severity" class="form-control form-control-sm" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Predicate script</label>
                        <InputSelect @bind-Value="_form.PredicateScriptId" class="form-select form-select-sm">
                            <option value="">— pick script —</option>
                            @foreach (var s in _scripts) { <option value="@s.ScriptId">@s.Name</option> }
                        </InputSelect>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message template</label>
                    <InputTextArea @bind-Value="_form.MessageTemplate" class="form-control form-control-sm" rows="3"
                                   placeholder="{equipment.MachineCode} temperature out of range: {value}°C" />
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">HistorizeToAveva</label>
                        <div class="form-check form-switch">
                            <InputCheckbox @bind-Value="_form.HistorizeToAveva" class="form-check-input" />
                            <label class="form-check-label">Route to Wonderware sidecar</label>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Retain</label>
                        <div class="form-check form-switch">
                            <InputCheckbox @bind-Value="_form.Retain" class="form-check-input" />
                            <label class="form-check-label">Retain active alarms on restart</label>
                        </div>
                    </div>
                    <div class="col-md-4 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 alarm in deployments</label>
                        </div>
                    </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="/scripted-alarms" 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? ScriptedAlarmId { get; set; }
    private bool IsNew => string.IsNullOrEmpty(ScriptedAlarmId);

    private FormModel _form = new();
    private ScriptedAlarm? _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.ScriptedAlarms.AsNoTracking().FirstOrDefaultAsync(a => a.ScriptedAlarmId == ScriptedAlarmId);
            if (_existing is not null)
            {
                _form = new FormModel
                {
                    ScriptedAlarmId = _existing.ScriptedAlarmId,
                    Name = _existing.Name,
                    EquipmentId = _existing.EquipmentId,
                    AlarmType = _existing.AlarmType,
                    Severity = _existing.Severity,
                    PredicateScriptId = _existing.PredicateScriptId,
                    MessageTemplate = _existing.MessageTemplate,
                    HistorizeToAveva = _existing.HistorizeToAveva,
                    Retain = _existing.Retain,
                    Enabled = _existing.Enabled,
                    RowVersion = _existing.RowVersion,
                };
            }
        }
        _loaded = true;
    }

    private async Task SubmitAsync()
    {
        _busy = true; _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                if (await db.ScriptedAlarms.AnyAsync(a => a.ScriptedAlarmId == _form.ScriptedAlarmId))
                { _error = $"ScriptedAlarm '{_form.ScriptedAlarmId}' already exists."; return; }
                db.ScriptedAlarms.Add(new ScriptedAlarm
                {
                    ScriptedAlarmId = _form.ScriptedAlarmId,
                    EquipmentId = _form.EquipmentId,
                    Name = _form.Name,
                    AlarmType = _form.AlarmType,
                    Severity = _form.Severity,
                    MessageTemplate = _form.MessageTemplate,
                    PredicateScriptId = _form.PredicateScriptId,
                    HistorizeToAveva = _form.HistorizeToAveva,
                    Retain = _form.Retain,
                    Enabled = _form.Enabled,
                });
            }
            else
            {
                var entity = await db.ScriptedAlarms.FirstOrDefaultAsync(a => a.ScriptedAlarmId == ScriptedAlarmId);
                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.AlarmType = _form.AlarmType;
                entity.Severity = _form.Severity;
                entity.MessageTemplate = _form.MessageTemplate;
                entity.PredicateScriptId = _form.PredicateScriptId;
                entity.HistorizeToAveva = _form.HistorizeToAveva;
                entity.Retain = _form.Retain;
                entity.Enabled = _form.Enabled;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo("/scripted-alarms");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this scripted alarm 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.ScriptedAlarms.FirstOrDefaultAsync(a => a.ScriptedAlarmId == ScriptedAlarmId);
            if (entity is null) { Nav.NavigateTo("/scripted-alarms"); return; }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.ScriptedAlarms.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo("/scripted-alarms");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this alarm 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 ScriptedAlarmId { get; set; } = "";
        [Required] public string Name { get; set; } = "";
        [Required] public string EquipmentId { get; set; } = "";
        [Required] public string AlarmType { get; set; } = "LimitAlarm";
        [Range(1, 1000)] public int Severity { get; set; } = 500;
        [Required] public string PredicateScriptId { get; set; } = "";
        [Required] public string MessageTemplate { get; set; } = "";
        public bool HistorizeToAveva { get; set; } = true;
        public bool Retain { get; set; } = true;
        public bool Enabled { get; set; } = true;
        public byte[] RowVersion { get; set; } = [];
    }
}
