@page "/admin/api-keys/create"
@page "/admin/api-keys/{Id:int}/edit"
@using ScadaLink.Security
@using ScadaLink.Commons.Entities.InboundApi
@using ScadaLink.Commons.Interfaces.Repositories
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
@inject IInboundApiRepository InboundApiRepository
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <div class="d-flex align-items-center mb-3">
        @if (_saved)
        {
            <a href="/admin/api-keys" class="btn btn-outline-secondary btn-sm me-2">&larr; Back to API Keys</a>
        }
        else
        {
            <a href="/admin/api-keys" class="btn btn-outline-secondary btn-sm me-2">&larr; Back</a>
        }
        <h4 class="mb-0">@(_saved ? "API Key Created" : (_editingKey != null ? "Edit API Key" : "Add API Key"))</h4>
    </div>

    @if (_loading)
    {
        <LoadingSpinner IsLoading="true" />
    }
    else if (_saved && _newlyCreatedKeyValue != null)
    {
        <div class="alert alert-success">
            <strong>New API Key Created</strong>
            <div class="d-flex align-items-center mt-1">
                <code class="me-2">@_newlyCreatedKeyValue</code>
                <button class="btn btn-outline-secondary btn-sm py-0 px-1" @onclick="CopyKeyToClipboard">Copy</button>
            </div>
            <small class="text-muted d-block mt-1">Save this key now. It will not be shown again in full.</small>
        </div>
        <a href="/admin/api-keys" class="btn btn-primary btn-sm">Back to API Keys</a>
    }
    else if (_errorMessage != null)
    {
        <div class="alert alert-danger">@_errorMessage</div>
    }
    else
    {
        <div class="card">
            <div class="card-body">
                <div class="mb-2">
                    <label class="form-label small">Name</label>
                    <input type="text" class="form-control form-control-sm" @bind="_formName" />
                </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="SaveKey">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 ApiKey? _editingKey;
    private string _formName = string.Empty;
    private string? _formError;
    private string? _errorMessage;
    private string? _newlyCreatedKeyValue;
    private bool _loading = true;
    private bool _saved;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            if (Id.HasValue)
            {
                _editingKey = await InboundApiRepository.GetApiKeyByIdAsync(Id.Value);
                if (_editingKey == null)
                {
                    _errorMessage = $"API key with ID {Id.Value} not found.";
                }
                else
                {
                    _formName = _editingKey.Name;
                }
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"Failed to load API key: {ex.Message}";
        }
        _loading = false;
    }

    private async Task SaveKey()
    {
        _formError = null;
        if (string.IsNullOrWhiteSpace(_formName)) { _formError = "Name is required."; return; }

        try
        {
            if (_editingKey != null)
            {
                _editingKey.Name = _formName.Trim();
                await InboundApiRepository.UpdateApiKeyAsync(_editingKey);
                await InboundApiRepository.SaveChangesAsync();
                NavigationManager.NavigateTo("/admin/api-keys");
            }
            else
            {
                var keyValue = GenerateApiKey();
                var key = new ApiKey(_formName.Trim(), keyValue) { IsEnabled = true };
                await InboundApiRepository.AddApiKeyAsync(key);
                await InboundApiRepository.SaveChangesAsync();
                _newlyCreatedKeyValue = keyValue;
                _saved = true;
            }
        }
        catch (Exception ex)
        {
            _formError = $"Save failed: {ex.Message}";
        }
    }

    private void GoBack() => NavigationManager.NavigateTo("/admin/api-keys");

    private void CopyKeyToClipboard()
    {
        // Note: JS interop for clipboard would be needed for actual copy.
        // For now the key is displayed for manual copy.
    }

    private static string GenerateApiKey()
    {
        var bytes = new byte[32];
        using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
        rng.GetBytes(bytes);
        return Convert.ToBase64String(bytes).Replace("+", "").Replace("/", "").Replace("=", "")[..40];
    }
}
