@page "/admin/data-connections"
@using ScadaLink.Security
@using ScadaLink.Commons.Entities.Sites
@using ScadaLink.Commons.Interfaces.Repositories
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
@inject ISiteRepository SiteRepository
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0">Data Connections</h4>
        <button class="btn btn-primary btn-sm" @onclick='() => NavigationManager.NavigateTo("/admin/data-connections/create")'>Add Connection</button>
    </div>

    <ToastNotification @ref="_toast" />
    <ConfirmDialog @ref="_confirmDialog" />

    @if (_loading)
    {
        <LoadingSpinner IsLoading="true" />
    }
    else if (_errorMessage != null)
    {
        <div class="alert alert-danger">@_errorMessage</div>
    }
    else
    {
        <table class="table table-sm table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Protocol</th>
                    <th>Site</th>
                    <th>Primary Config</th>
                    <th>Backup Config</th>
                    <th style="width: 160px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                @if (_connections.Count == 0)
                {
                    <tr>
                        <td colspan="7" class="text-muted text-center">No data connections configured.</td>
                    </tr>
                }
                @foreach (var conn in _connections)
                {
                    <tr>
                        <td>@conn.Id</td>
                        <td>@conn.Name</td>
                        <td><span class="badge bg-secondary">@conn.Protocol</span></td>
                        <td>@(_siteLookup.GetValueOrDefault(conn.SiteId)?.Name ?? $"Site {conn.SiteId}")</td>
                        <td class="text-muted small text-truncate" style="max-width: 300px;">@(conn.PrimaryConfiguration ?? "—")</td>
                        <td class="text-muted small text-truncate" style="max-width: 300px;">@(conn.BackupConfiguration ?? "—")</td>
                        <td>
                            <button class="btn btn-outline-primary btn-sm py-0 px-1 me-1"
                                    @onclick='() => NavigationManager.NavigateTo($"/admin/data-connections/{conn.Id}/edit")'>Edit</button>
                            <button class="btn btn-outline-danger btn-sm py-0 px-1"
                                    @onclick="() => DeleteConnection(conn)">Delete</button>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    }
</div>

@code {
    private List<DataConnection> _connections = new();
    private Dictionary<int, Site> _siteLookup = new();
    private bool _loading = true;
    private string? _errorMessage;

    private ToastNotification _toast = default!;
    private ConfirmDialog _confirmDialog = default!;

    protected override async Task OnInitializedAsync()
    {
        await LoadDataAsync();
    }

    private async Task LoadDataAsync()
    {
        _loading = true;
        _errorMessage = null;
        try
        {
            var sites = await SiteRepository.GetAllSitesAsync();
            _siteLookup = sites.ToDictionary(s => s.Id);
            _connections = (await SiteRepository.GetAllDataConnectionsAsync()).ToList();
        }
        catch (Exception ex)
        {
            _errorMessage = $"Failed to load data: {ex.Message}";
        }
        _loading = false;
    }

    private async Task DeleteConnection(DataConnection conn)
    {
        var confirmed = await _confirmDialog.ShowAsync(
            $"Delete data connection '{conn.Name}'?", "Delete Connection");
        if (!confirmed) return;

        try
        {
            await SiteRepository.DeleteDataConnectionAsync(conn.Id);
            await SiteRepository.SaveChangesAsync();
            _toast.ShowSuccess($"Connection '{conn.Name}' deleted.");
            await LoadDataAsync();
        }
        catch (Exception ex)
        {
            _toast.ShowError($"Delete failed: {ex.Message}");
        }
    }
}
