@page "/admin/data-connections/create"
@page "/admin/data-connections/{Id:int}/edit"
@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 align-items-center mb-3">
        <button class="btn btn-outline-secondary btn-sm me-3" @onclick="GoBack">&larr; Back</button>
        <h4 class="mb-0">@(Id.HasValue ? "Edit Data Connection" : "Add Data Connection")</h4>
    </div>

    @if (_loading)
    {
        <LoadingSpinner IsLoading="true" />
    }
    else
    {
        <div class="card mb-3">
            <div class="card-body">
                @if (Id.HasValue)
                {
                    <div class="mb-2">
                        <label class="form-label small">Site</label>
                        <input type="text" class="form-control form-control-sm" value="@(_siteName)" disabled />
                    </div>
                }
                else
                {
                    <div class="mb-2">
                        <label class="form-label small">Site</label>
                        <select class="form-select form-select-sm" @bind="_formSiteId">
                            <option value="0">Select site...</option>
                            @foreach (var site in _sites)
                            {
                                <option value="@site.Id">@site.Name</option>
                            }
                        </select>
                    </div>
                }
                <div class="mb-2">
                    <label class="form-label small">Name</label>
                    <input type="text" class="form-control form-control-sm" @bind="_formName" />
                </div>
                <div class="mb-2">
                    <label class="form-label small">Protocol</label>
                    <select class="form-select form-select-sm" @bind="_formProtocol">
                        <option value="">Select...</option>
                        <option value="OpcUa">OPC UA</option>
                        <option value="LmxProxy">LMX Proxy</option>
                        <option value="Custom">Custom</option>
                    </select>
                </div>
                <div class="mb-2">
                    <label class="form-label small">Primary Endpoint Configuration</label>
                    <input type="text" class="form-control form-control-sm" @bind="_formConfiguration"
                           placeholder='e.g. {"endpoint":"opc.tcp://..."}' />
                </div>

                @if (!_showBackup)
                {
                    <div class="mb-3">
                        <button type="button" class="btn btn-outline-secondary btn-sm"
                                @onclick="() => _showBackup = true">
                            Add Backup Endpoint
                        </button>
                    </div>
                }
                else
                {
                    <div class="mb-3">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <label class="form-label small mb-0">Backup Endpoint Configuration</label>
                            <button type="button" class="btn btn-outline-danger btn-sm"
                                    @onclick="RemoveBackup">
                                Remove Backup
                            </button>
                        </div>
                        <textarea class="form-control form-control-sm" rows="4"
                                  @bind="_formBackupConfiguration"
                                  placeholder='{"Host": "backup-host", "Port": 50101}' />
                    </div>

                    <div class="mb-3">
                        <label class="form-label small">Failover Retry Count</label>
                        <input type="number" class="form-control form-control-sm" style="max-width: 120px;"
                               min="1" max="20"
                               @bind="_formFailoverRetryCount" />
                        <div class="form-text">Retries on active endpoint before switching to backup (default: 3)</div>
                    </div>
                }
                @if (_formError != null)
                {
                    <div class="text-danger small mt-2">@_formError</div>
                }
                <div class="mt-3">
                    <button class="btn btn-success btn-sm me-1" @onclick="SaveConnection">Save</button>
                    <button class="btn btn-outline-secondary btn-sm" @onclick="GoBack">Cancel</button>
                </div>
            </div>
        </div>
    }
</div>

@code {
    [Parameter] public int? Id { get; set; }

    private bool _loading = true;
    private DataConnection? _editingConnection;
    private List<Site> _sites = new();
    private int _formSiteId;
    private string _siteName = string.Empty;
    private string _formName = string.Empty;
    private string _formProtocol = string.Empty;
    private string? _formConfiguration;
    private bool _showBackup;
    private string? _formBackupConfiguration;
    private int _formFailoverRetryCount = 3;
    private string? _formError;

    protected override async Task OnInitializedAsync()
    {
        _sites = (await SiteRepository.GetAllSitesAsync()).ToList();

        if (Id.HasValue)
        {
            try
            {
                _editingConnection = await SiteRepository.GetDataConnectionByIdAsync(Id.Value);
                if (_editingConnection != null)
                {
                    _formSiteId = _editingConnection.SiteId;
                    _siteName = _sites.FirstOrDefault(s => s.Id == _formSiteId)?.Name ?? $"Site {_formSiteId}";
                    _formName = _editingConnection.Name;
                    _formProtocol = _editingConnection.Protocol;
                    _formConfiguration = _editingConnection.PrimaryConfiguration;
                    _formBackupConfiguration = _editingConnection.BackupConfiguration;
                    _formFailoverRetryCount = _editingConnection.FailoverRetryCount;
                    _showBackup = _editingConnection.BackupConfiguration != null;
                }
            }
            catch (Exception ex)
            {
                _formError = $"Failed to load connection: {ex.Message}";
            }
        }
        _loading = false;
    }

    private async Task SaveConnection()
    {
        _formError = null;
        if (_formSiteId == 0) { _formError = "Site is required."; return; }
        if (string.IsNullOrWhiteSpace(_formName)) { _formError = "Name is required."; return; }
        if (string.IsNullOrWhiteSpace(_formProtocol)) { _formError = "Protocol is required."; return; }

        try
        {
            if (_editingConnection != null)
            {
                _editingConnection.Name = _formName.Trim();
                _editingConnection.Protocol = _formProtocol;
                _editingConnection.PrimaryConfiguration = _formConfiguration?.Trim();
                _editingConnection.BackupConfiguration = _showBackup ? _formBackupConfiguration?.Trim() : null;
                _editingConnection.FailoverRetryCount = _showBackup ? _formFailoverRetryCount : 3;
                await SiteRepository.UpdateDataConnectionAsync(_editingConnection);
            }
            else
            {
                var conn = new DataConnection(_formName.Trim(), _formProtocol, _formSiteId)
                {
                    PrimaryConfiguration = _formConfiguration?.Trim(),
                    BackupConfiguration = _showBackup ? _formBackupConfiguration?.Trim() : null,
                    FailoverRetryCount = _showBackup ? _formFailoverRetryCount : 3
                };
                await SiteRepository.AddDataConnectionAsync(conn);
            }
            await SiteRepository.SaveChangesAsync();
            NavigationManager.NavigateTo("/admin/data-connections");
        }
        catch (Exception ex)
        {
            _formError = $"Save failed: {ex.Message}";
        }
    }

    private void RemoveBackup()
    {
        _showBackup = false;
        _formBackupConfiguration = null;
        _formFailoverRetryCount = 3;
    }

    private void GoBack()
    {
        NavigationManager.NavigateTo("/admin/data-connections");
    }
}
