@page "/reservations"
@using ZB.MOM.WW.OtOpcUa.Admin.Services
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Policy = "CanPublish")]
@inject ReservationService ReservationSvc

<h1 class="mb-4">External-ID reservations</h1>
<p class="text-muted">
    Fleet-wide ZTag + SAPID reservation state (decision #124). Releasing a reservation is a
    FleetAdmin-only audit-logged action — only release when the physical asset is permanently
    retired and its ID needs to be reused by a different equipment.
</p>

<h4 class="mt-4">Active</h4>
@if (_active is null) { <p>Loading…</p> }
else if (_active.Count == 0) { <p class="text-muted">No active reservations.</p> }
else
{
    <table class="table table-sm">
        <thead><tr><th>Kind</th><th>Value</th><th>EquipmentUuid</th><th>Cluster</th><th>First published</th><th>Last published</th><th></th></tr></thead>
        <tbody>
        @foreach (var r in _active)
        {
            <tr>
                <td><code>@r.Kind</code></td>
                <td><code>@r.Value</code></td>
                <td><code>@r.EquipmentUuid</code></td>
                <td>@r.ClusterId</td>
                <td><small>@r.FirstPublishedAt.ToString("u") by @r.FirstPublishedBy</small></td>
                <td><small>@r.LastPublishedAt.ToString("u")</small></td>
                <td><button class="btn btn-sm btn-outline-danger" @onclick='() => OpenReleaseDialog(r)'>Release…</button></td>
            </tr>
        }
        </tbody>
    </table>
}

<h4 class="mt-4">Released (most recent 100)</h4>
@if (_released is null) { <p>Loading…</p> }
else if (_released.Count == 0) { <p class="text-muted">No released reservations yet.</p> }
else
{
    <table class="table table-sm">
        <thead><tr><th>Kind</th><th>Value</th><th>Released at</th><th>By</th><th>Reason</th></tr></thead>
        <tbody>
        @foreach (var r in _released)
        {
            <tr><td><code>@r.Kind</code></td><td><code>@r.Value</code></td><td>@r.ReleasedAt?.ToString("u")</td><td>@r.ReleasedBy</td><td>@r.ReleaseReason</td></tr>
        }
        </tbody>
    </table>
}

@if (_releasing is not null)
{
    <div class="modal show d-block" tabindex="-1" style="background-color: rgba(0,0,0,0.5);">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Release reservation <code>@_releasing.Kind</code> = <code>@_releasing.Value</code></h5>
                </div>
                <div class="modal-body">
                    <p>This makes the (Kind, Value) pair available for a different EquipmentUuid in a future publish. Audit-logged.</p>
                    <label class="form-label">Reason (required)</label>
                    <textarea class="form-control" rows="3" @bind="_reason"></textarea>
                    @if (_error is not null) { <div class="alert alert-danger mt-2">@_error</div> }
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" @onclick='() => _releasing = null'>Cancel</button>
                    <button class="btn btn-danger" @onclick="ReleaseAsync" disabled="@_busy">Release</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    private List<ExternalIdReservation>? _active;
    private List<ExternalIdReservation>? _released;
    private ExternalIdReservation? _releasing;
    private string _reason = string.Empty;
    private bool _busy;
    private string? _error;

    protected override async Task OnInitializedAsync() => await ReloadAsync();

    private async Task ReloadAsync()
    {
        _active = await ReservationSvc.ListActiveAsync(CancellationToken.None);
        _released = await ReservationSvc.ListReleasedAsync(CancellationToken.None);
    }

    private void OpenReleaseDialog(ExternalIdReservation r)
    {
        _releasing = r;
        _reason = string.Empty;
        _error = null;
    }

    private async Task ReleaseAsync()
    {
        if (_releasing is null || string.IsNullOrWhiteSpace(_reason)) { _error = "Reason is required"; return; }
        _busy = true;
        try
        {
            await ReservationSvc.ReleaseAsync(_releasing.Kind.ToString(), _releasing.Value, _reason, CancellationToken.None);
            _releasing = null;
            await ReloadAsync();
        }
        catch (Exception ex) { _error = ex.Message; }
        finally { _busy = false; }
    }
}
