@page "/inventur/vorbereiten"
@attribute [Authorize]
@using System.Text.Json
@using Microsoft.AspNetCore.Components.Web
@inject IJSRuntime JS

<h3>Inventur – Vorbereitung</h3>

<div class="mb-3">
   
    <input @ref="qrCodeRef" id="qrInput"
           class="form-control form-control-lg"
           placeholder="QR scannen"
           @bind="qrText"
           @bind:event="oninput"
           @bind:after="OnQrChanged"
           @onkeydown="OnQrKey" />
    <div class="form-text">
        Scannen Sie den QR-Code aus dem Lambertz-Portal, um die Inventur zu starten.
    </div>
</div>

@* <button class="btn btn-primary me-2" @onclick="ApplyQrAsync" disabled="@(!_jsReady)">
    Übernehmen
</button>

<button class="btn btn-outline-danger" @onclick="ClearAsync" disabled="@(!_jsReady)">
    Inventur-Config löschen
</button> *@

@if (!string.IsNullOrEmpty(status))
{
    <div class="alert @(ok ? "alert-success" : "alert-danger") mt-3 py-2 mb-0" role="alert">
        @status
    </div>
}

<hr />

@if (!_jsReady)
{
    <div class="text-muted">Lade aktuelle Einstellungen …</div>
}
else
{
    <h5>Aktuelle lokale Einstellungen</h5>
    <dl class="row">
        <dt class="col-sm-2">Filial-ID</dt>
        <dd class="col-sm-10">@currentFilialId</dd>

        <dt class="col-sm-2">Inventur-ID</dt>
        <dd class="col-sm-10">@currentInventurId</dd>
    </dl>
}

@code {
    private string? qrText;
    private string? status;
    private bool ok;

    private bool focusQrCode = true;

    private ElementReference qrCodeRef;

    private string? currentFilialId;
    private int? currentInventurId;

    private bool _jsReady;
    private CancellationTokenSource? _debounceCts;

    // QR-JSON: {"filialId":"7","inventurId":123}
    private class QrConfig
    {
        public string? FilialId { get; set; }
        public int? InventurId { get; set; }
    }

    protected override Task OnInitializedAsync() => Task.CompletedTask;

       
   

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return;
        await LoadCurrentAsync();
        _jsReady = true;
        StateHasChanged();


        if (focusQrCode)
        {
            focusQrCode = false;
            await qrCodeRef.FocusAsync();
        }
    }

    private async Task LoadCurrentAsync()
    {
        try
        {
            currentFilialId = (await GetLsAsync("scannerpilot.filialId"))?.Trim('"');

            var invenStr = (await GetLsAsync("scannerpilot.inventurId"))?.Trim('"');
            currentInventurId = int.TryParse(invenStr, out var inven) ? inven : null;
        }
        catch { /* ignorieren */ }
    }

    private async Task<string?> GetLsAsync(string key)
    {
        try { return await JS.InvokeAsync<string?>("localStorage.getItem", key); }
        catch { return null; }
    }
    private async Task SetLsAsync(string key, string value)
    {
        try { await JS.InvokeVoidAsync("localStorage.setItem", key, value); }
        catch { }
    }
    private async Task RemoveLsAsync(string key)
    {
        try { await JS.InvokeVoidAsync("localStorage.removeItem", key); }
        catch { }
    }

    // Scanner schickt oft Enter am Ende
    private async Task OnQrKey(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
            await ApplyQrAsync();
    }

    // Debounce auf oninput: 200ms Ruhe + gültiges JSON => übernehmen
    private void OnQrChanged()
    {
        if (!_jsReady) return;

        _debounceCts?.Cancel();
        _debounceCts = new CancellationTokenSource();
        var token = _debounceCts.Token;

        _ = Task.Run(async () =>
        {
            try
            {
                await Task.Delay(200, token);
                if (token.IsCancellationRequested) return;

                var text = qrText?.Trim();
                if (string.IsNullOrWhiteSpace(text)) return;

                // nur wenn wirklich parsebar (schützt vor halben Scans)
                try
                {
                    _ = JsonSerializer.Deserialize<QrConfig>(text, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                }
                catch
                {
                    return; // noch unvollständig – nichts tun
                }

                await InvokeAsync(ApplyQrAsync);
            }
            catch (TaskCanceledException) { /* ignoriert */ }
        }, token);
    }

    private async Task ApplyQrAsync()
    {
        status = null; ok = false;

        if (!_jsReady)
        {
            status = "Seite initialisiert noch – bitte kurz warten.";
            return;
        }

        if (string.IsNullOrWhiteSpace(qrText))
        {
            status = "Bitte zuerst einen QR-Code scannen (JSON).";
            return;
        }

        try
        {
            var cfg = JsonSerializer.Deserialize<QrConfig>(qrText, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

            if (cfg is null)
            {
                status = "QR-Code konnte nicht gelesen werden (leere Daten).";
                return;
            }

            if (string.IsNullOrWhiteSpace(cfg.FilialId) || cfg.InventurId is null)
            {
                status = "Ihr QR-Code ist fehlerhaft.";
                return;
            }

            // speichern
            await SetLsAsync("scannerpilot.filialId", cfg.FilialId);
            await SetLsAsync("scannerpilot.inventurId", cfg.InventurId.Value.ToString());

            // UI aktualisieren
            await LoadCurrentAsync();

            ok = true;
            status = $"Einstellungen übernommen: Filiale {cfg.FilialId}, Inventur {cfg.InventurId.Value}.";
            qrText = string.Empty;

            // Erfolgshinweis nach 2,5s automatisch ausblenden
            _ = Task.Run(async () =>
            {
                await Task.Delay(2500);
                await InvokeAsync(() => { status = null; StateHasChanged(); });
            });
        }
        catch (JsonException ex)
        {
            ok = false;
            status = "Ungültiges JSON im QR-Code: " + ex.Message;
        }
        catch (Exception ex)
        {
            ok = false;
            status = "Fehler beim Speichern: " + ex.Message;
        }
    }

    private async Task ClearAsync()
    {
        if (!_jsReady)
        {
            ok = false;
            status = "Seite initialisiert noch – bitte kurz warten.";
            return;
        }

        try
        {
            await RemoveLsAsync("scannerpilot.filialId");
            await RemoveLsAsync("scannerpilot.inventurId");
            currentFilialId = null;
            currentInventurId = null;

            ok = true;
            status = "Filial-ID und Inventur-ID wurden gelöscht.";

            // Hinweis nach 2,5s ausblenden
            _ = Task.Run(async () =>
            {
                await Task.Delay(2500);
                await InvokeAsync(() => { status = null; StateHasChanged(); });
            });
        }
        catch (Exception ex)
        {
            ok = false;
            status = "Fehler beim Löschen: " + ex.Message;
        }
    }
}
