@page "/clusters/{ClusterId}/uns/lines/new"
@page "/clusters/{ClusterId}/uns/lines/{UnsLineId}"
@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 UNS line" : "Edit UNS line") &middot; <span class="mono">@ClusterId</span></h4>
    <a href="/clusters/@ClusterId/uns" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>

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

@if (!_loaded)
{
    <p>Loading…</p>
}
else if (!IsNew && _existing is null)
{
    <section class="panel notice rise" style="animation-delay:.02s">
        Line <span class="mono">@UnsLineId</span> was not found.
    </section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="unsLineEdit">
        <DataAnnotationsValidator />
        <section class="panel rise" style="animation-delay:.02s">
            <div class="panel-head">UNS line (level 4)</div>
            <div style="padding:1rem">
                <div class="mb-3">
                    <label class="form-label" for="lid">UnsLineId</label>
                    <InputText id="lid" @bind-Value="_form.UnsLineId" disabled="@(!IsNew)"
                               class="form-control form-control-sm mono" />
                </div>
                <div class="mb-3">
                    <label class="form-label" for="area">Parent area</label>
                    <InputSelect id="area" @bind-Value="_form.UnsAreaId" class="form-select form-select-sm">
                        @foreach (var area in _areas)
                        {
                            <option value="@area.UnsAreaId">@area.UnsAreaId &mdash; @area.Name</option>
                        }
                    </InputSelect>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="name">Name</label>
                    <InputText id="name" @bind-Value="_form.Name" class="form-control form-control-sm" />
                </div>
                <div class="mb-3">
                    <label class="form-label" for="notes">Notes</label>
                    <InputTextArea id="notes" @bind-Value="_form.Notes" class="form-control form-control-sm" rows="3" />
                </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/uns" 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 ClusterId { get; set; } = "";
    [Parameter] public string? UnsLineId { get; set; }

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

    private FormModel _form = new();
    private UnsLine? _existing;
    private List<UnsArea> _areas = new();
    private bool _loaded;
    private bool _busy;
    private string? _error;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _areas = await db.UnsAreas.AsNoTracking()
            .Where(a => a.ClusterId == ClusterId)
            .OrderBy(a => a.UnsAreaId)
            .ToListAsync();

        if (!IsNew)
        {
            _existing = await db.UnsLines.AsNoTracking()
                .FirstOrDefaultAsync(l => l.UnsLineId == UnsLineId);
            if (_existing is not null)
            {
                _form = new FormModel
                {
                    UnsLineId = _existing.UnsLineId,
                    UnsAreaId = _existing.UnsAreaId,
                    Name = _existing.Name,
                    Notes = _existing.Notes,
                    RowVersion = _existing.RowVersion,
                };
            }
        }
        else
        {
            _form.UnsAreaId = _areas.FirstOrDefault()?.UnsAreaId ?? "";
        }
        _loaded = true;
    }

    private async Task SubmitAsync()
    {
        _busy = true; _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                if (await db.UnsLines.AnyAsync(l => l.UnsLineId == _form.UnsLineId))
                { _error = $"Line '{_form.UnsLineId}' already exists."; return; }
                db.UnsLines.Add(new UnsLine
                {
                    UnsLineId = _form.UnsLineId,
                    UnsAreaId = _form.UnsAreaId,
                    Name = _form.Name,
                    Notes = string.IsNullOrWhiteSpace(_form.Notes) ? null : _form.Notes,
                });
            }
            else
            {
                var entity = await db.UnsLines.FirstOrDefaultAsync(l => l.UnsLineId == UnsLineId);
                if (entity is null) { _error = "Row no longer exists."; return; }
                db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
                entity.UnsAreaId = _form.UnsAreaId;
                entity.Name = _form.Name;
                entity.Notes = string.IsNullOrWhiteSpace(_form.Notes) ? null : _form.Notes;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/uns");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this line 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.UnsLines.FirstOrDefaultAsync(l => l.UnsLineId == UnsLineId);
            if (entity is null) { Nav.NavigateTo($"/clusters/{ClusterId}/uns"); return; }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.UnsLines.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/uns");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this line while you were viewing it."; }
        catch (Exception ex) { _error = $"Delete failed: {ex.Message}. Likely because equipment still references this line — remove or re-home it first."; }
        finally { _busy = false; }
    }

    private sealed class FormModel
    {
        [Required, RegularExpression("^[A-Za-z0-9_-]+$")] public string UnsLineId { get; set; } = "";
        [Required] public string UnsAreaId { get; set; } = "";
        [Required] public string Name { get; set; } = "";
        public string? Notes { get; set; }
        public byte[] RowVersion { get; set; } = [];
    }
}
