@page "/design/shared-scripts/create"
@page "/design/shared-scripts/{Id:int}/edit"
@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 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 Shared Script: {_formName}" : "New Shared Script")</h4>
    </div>

    @if (_loading)
    {
        <LoadingSpinner IsLoading="true" />
    }
    else
    {
        <div class="card mb-3">
            <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"
                           disabled="@(Id.HasValue)" />
                </div>
                <div class="mb-2">
                    <label class="form-label small">Parameters (JSON)</label>
                    <input type="text" class="form-control form-control-sm" @bind="_formParameters"
                           placeholder='e.g. [{"name":"x","type":"Int32"}]' />
                </div>
                <div class="mb-2">
                    <label class="form-label small">Return Definition (JSON)</label>
                    <input type="text" class="form-control form-control-sm" @bind="_formReturn"
                           placeholder='e.g. {"type":"Boolean"}' />
                </div>
                <div class="mb-2">
                    <label class="form-label small">Code</label>
                    <textarea class="form-control form-control-sm font-monospace" rows="10" @bind="_formCode"
                              style="font-size: 0.8rem;"></textarea>
                </div>
                @if (_formError != null)
                {
                    <div class="text-danger small mt-2">@_formError</div>
                }
                @if (_syntaxCheckResult != null)
                {
                    <div class="@(_syntaxCheckPassed ? "text-success" : "text-danger") small mt-1">@_syntaxCheckResult</div>
                }
                <div class="mt-3">
                    <button class="btn btn-success btn-sm me-1" @onclick="SaveScript">Save</button>
                    <button class="btn btn-outline-info btn-sm me-1" @onclick="CheckCompilation">Check Syntax</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;
    private string _formName = string.Empty;
    private string _formCode = string.Empty;
    private string? _formParameters;
    private string? _formReturn;
    private string? _formError;
    private string? _syntaxCheckResult;
    private bool _syntaxCheckPassed;

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

    protected override async Task OnInitializedAsync()
    {
        if (Id.HasValue)
        {
            _loading = true;
            try
            {
                var scripts = await SharedScriptService.GetAllSharedScriptsAsync();
                var script = scripts.FirstOrDefault(s => s.Id == Id.Value);
                if (script != null)
                {
                    _formName = script.Name;
                    _formCode = script.Code;
                    _formParameters = script.ParameterDefinitions;
                    _formReturn = script.ReturnDefinition;
                }
                else
                {
                    _formError = $"Shared script with ID {Id.Value} not found.";
                }
            }
            catch (Exception ex)
            {
                _formError = $"Failed to load script: {ex.Message}";
            }
            _loading = false;
        }
    }

    private void GoBack()
    {
        NavigationManager.NavigateTo("/design/shared-scripts");
    }

    private void CheckCompilation()
    {
        var syntaxError = ValidateSyntaxLocally(_formCode);
        if (syntaxError == null)
        {
            _syntaxCheckResult = "Syntax check passed.";
            _syntaxCheckPassed = true;
        }
        else
        {
            _syntaxCheckResult = syntaxError;
            _syntaxCheckPassed = false;
        }
    }

    private async Task SaveScript()
    {
        _formError = null;
        _syntaxCheckResult = null;

        try
        {
            if (Id.HasValue)
            {
                var user = await GetCurrentUserAsync();
                var result = await SharedScriptService.UpdateSharedScriptAsync(
                    Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user);
                if (result.IsSuccess)
                {
                    NavigationManager.NavigateTo("/design/shared-scripts");
                }
                else
                {
                    _formError = result.Error;
                }
            }
            else
            {
                var user = await GetCurrentUserAsync();
                var result = await SharedScriptService.CreateSharedScriptAsync(
                    _formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user);
                if (result.IsSuccess)
                {
                    NavigationManager.NavigateTo("/design/shared-scripts");
                }
                else
                {
                    _formError = result.Error;
                }
            }
        }
        catch (Exception ex)
        {
            _formError = $"Save failed: {ex.Message}";
        }
    }

    /// <summary>
    /// Basic syntax check: balanced braces/brackets/parens.
    /// Mirrors the internal SharedScriptService.ValidateSyntax logic.
    /// </summary>
    private static string? ValidateSyntaxLocally(string code)
    {
        if (string.IsNullOrWhiteSpace(code)) return "Script code cannot be empty.";
        int brace = 0, bracket = 0, paren = 0;
        foreach (var ch in code)
        {
            switch (ch) { case '{': brace++; break; case '}': brace--; break; case '[': bracket++; break; case ']': bracket--; break; case '(': paren++; break; case ')': paren--; break; }
            if (brace < 0) return "Syntax error: unmatched closing brace '}'.";
            if (bracket < 0) return "Syntax error: unmatched closing bracket ']'.";
            if (paren < 0) return "Syntax error: unmatched closing parenthesis ')'.";
        }
        if (brace != 0) return "Syntax error: unmatched opening brace '{'.";
        if (bracket != 0) return "Syntax error: unmatched opening bracket '['.";
        if (paren != 0) return "Syntax error: unmatched opening parenthesis '('.";
        return null;
    }
}
