@page "/alarms/historian"
@using ZB.MOM.WW.OtOpcUa.Admin.Services
@using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian
@inject HistorianDiagnosticsService Diag

<h1>Alarm historian</h1>
<p class="text-muted">Local store-and-forward queue that ships alarm events to Aveva Historian via Galaxy.Host.</p>

<div class="card mb-3">
    <div class="card-body">
        <div class="row">
            <div class="col-md-3">
                <small class="text-muted">Drain state</small>
                <h4><span class="badge @BadgeFor(_status.DrainState)">@_status.DrainState</span></h4>
            </div>
            <div class="col-md-3">
                <small class="text-muted">Queue depth</small>
                <h4>@_status.QueueDepth.ToString("N0")</h4>
            </div>
            <div class="col-md-3">
                <small class="text-muted">Dead-letter depth</small>
                <h4 class="@(_status.DeadLetterDepth > 0 ? "text-warning" : "")">@_status.DeadLetterDepth.ToString("N0")</h4>
            </div>
            <div class="col-md-3">
                <small class="text-muted">Last success</small>
                <h4>@(_status.LastSuccessUtc?.ToString("u") ?? "—")</h4>
            </div>
        </div>

        @if (!string.IsNullOrEmpty(_status.LastError))
        {
            <div class="alert alert-warning mt-3 mb-0">
                <strong>Last error:</strong> @_status.LastError
            </div>
        }
    </div>
</div>

<div class="d-flex gap-2">
    <button class="btn btn-outline-secondary" @onclick="RefreshAsync">Refresh</button>
    <button class="btn btn-warning" disabled="@(_status.DeadLetterDepth == 0)" @onclick="RetryDeadLetteredAsync">
        Retry dead-lettered (@_status.DeadLetterDepth)
    </button>
</div>

@if (_retryResult is not null)
{
    <div class="alert alert-success mt-3">Requeued @_retryResult row(s) for retry.</div>
}

@code {
    private HistorianSinkStatus _status = new(0, 0, null, null, null, HistorianDrainState.Disabled);
    private int? _retryResult;

    protected override void OnInitialized() => _status = Diag.GetStatus();

    private Task RefreshAsync()
    {
        _status = Diag.GetStatus();
        _retryResult = null;
        return Task.CompletedTask;
    }

    private Task RetryDeadLetteredAsync()
    {
        _retryResult = Diag.TryRetryDeadLettered();
        _status = Diag.GetStatus();
        return Task.CompletedTask;
    }

    private static string BadgeFor(HistorianDrainState s) => s switch
    {
        HistorianDrainState.Idle => "bg-success",
        HistorianDrainState.Draining => "bg-info",
        HistorianDrainState.BackingOff => "bg-warning text-dark",
        HistorianDrainState.Disabled => "bg-secondary",
        _ => "bg-secondary",
    };
}
