@page "/design/shared-scripts"
@using ScadaLink.Security
@using ScadaLink.Commons.Entities.Scripts
@using ScadaLink.Commons.Interfaces.Repositories
@using ScadaLink.TemplateEngine
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject SharedScriptService SharedScriptService
@inject AuthenticationStateProvider AuthStateProvider
@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">Shared Scripts</h4>
        <button class="btn btn-primary btn-sm" @onclick='() => NavigationManager.NavigateTo("/design/shared-scripts/create")'>New Script</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>Code (preview)</th>
                    <th>Parameters</th>
                    <th>Returns</th>
                    <th style="width: 160px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                @if (_scripts.Count == 0)
                {
                    <tr>
                        <td colspan="6" class="text-muted text-center">No shared scripts configured.</td>
                    </tr>
                }
                @foreach (var script in _scripts)
                {
                    <tr>
                        <td>@script.Id</td>
                        <td><strong>@script.Name</strong></td>
                        <td class="small text-muted font-monospace text-truncate" style="max-width: 300px;">
                            @script.Code[..Math.Min(60, script.Code.Length)]@(script.Code.Length > 60 ? "..." : "")
                        </td>
                        <td class="small text-muted">@(script.ParameterDefinitions ?? "—")</td>
                        <td class="small text-muted">@(script.ReturnDefinition ?? "—")</td>
                        <td>
                            <button class="btn btn-outline-primary btn-sm py-0 px-1 me-1"
                                    @onclick='() => NavigationManager.NavigateTo($"/design/shared-scripts/{script.Id}/edit")'>Edit</button>
                            <button class="btn btn-outline-danger btn-sm py-0 px-1"
                                    @onclick="() => DeleteScript(script)">Delete</button>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    }
</div>

@code {
    private async Task<string> GetCurrentUserAsync()
    {
        var authState = await AuthStateProvider.GetAuthenticationStateAsync();
        return authState.User.FindFirst("Username")?.Value ?? "unknown";
    }

    private List<SharedScript> _scripts = 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
        {
            _scripts = (await SharedScriptService.GetAllSharedScriptsAsync()).ToList();
        }
        catch (Exception ex)
        {
            _errorMessage = $"Failed to load shared scripts: {ex.Message}";
        }
        _loading = false;
    }

    private async Task DeleteScript(SharedScript script)
    {
        var confirmed = await _confirmDialog.ShowAsync(
            $"Delete shared script '{script.Name}'?", "Delete Shared Script");
        if (!confirmed) return;

        try
        {
            var user = await GetCurrentUserAsync();
            var result = await SharedScriptService.DeleteSharedScriptAsync(script.Id, user);
            if (result.IsSuccess)
            {
                _toast.ShowSuccess($"Script '{script.Name}' deleted.");
                await LoadDataAsync();
            }
            else
            {
                _toast.ShowError(result.Error);
            }
        }
        catch (Exception ex)
        {
            _toast.ShowError($"Delete failed: {ex.Message}");
        }
    }
}
