@page "/stations/{customerId:int}"
@using FilterCair.Shared.Models
@inject FilterCair.Client.Services.API.StationService StationService
@inject FilterCair.Client.Services.API.FilterService FilterService
@inject NavigationManager Nav
@inject IJSRuntime JS

<PageTitle>Stationen</PageTitle>

<div class="container py-4">
    <h4 class="text-primary text-center mb-4">
        <i class="bi bi-geo-alt me-2"></i> Stationen der Fabrik
    </h4>

    <!-- QR Scanner -->
    <div class="text-center mb-4">
        <video id="video" autoplay playsinline class="border rounded shadow-sm"
               style="width:100%;max-width:420px;"></video>

        @if (!string.IsNullOrEmpty(scanResult))
        {
            <div class="alert alert-success mt-3">
                <strong>QR erkannt:</strong> @scanResult
            </div>
        }

        <div class="mt-3">
            <button class="btn btn-secondary me-2" @onclick="StartScan">🔄 Neu starten</button>
            <button class="btn btn-outline-danger" @onclick="StopScan">⏹ Stop</button>
        </div>
    </div>

    <hr />

    <!-- Stationsliste -->
    @if (isLoading)
    {
        <div class="text-center text-muted py-5">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-3">Lade Stationen...</p>
        </div>
    }
    else if (stations.Count == 0)
    {
        <div class="alert alert-info text-center">
            Keine Stationen gefunden.
        </div>
    }
    else
    {
        <div class="row g-3 justify-content-center">
            @foreach (var s in stations)
            {
                <div class="col-12 col-md-6 col-lg-4">
                    <div class="card shadow-sm border-0 station-card h-100"
                         @onclick="() => SelectStation(s)">
                        <div class="card-body">
                            <h5 class="fw-semibold text-primary mb-2">
                                <i class="bi bi-building me-1"></i> @s.Name
                            </h5>
                            <p class="text-muted small mb-1">
                                <i class="bi bi-geo me-1"></i> @s.Standort
                            </p>
                            <p class="text-muted small mb-0">@s.Beschreibung</p>
                        </div>
                    </div>
                </div>
            }
        </div>
    }
</div>

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

    private List<StationModel> stations = new();
    private string? scanResult;
    private bool isLoading = true;

    protected override async Task OnInitializedAsync()
    {
        await LoadStations();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync("QRScanner.init", DotNetObjectReference.Create(this));
        }
    }

    private async Task LoadStations()
    {
        try
        {
            isLoading = true;
            stations = await StationService.GetStationsByCustomerAsync(customerId);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ Fehler beim Laden der Stationen: {ex.Message}");
        }
        finally
        {
            isLoading = false;
        }
    }

    private void SelectStation(StationModel s)
    {
        Nav.NavigateTo($"/stations/{customerId}/filters/{s.Id}");
    }

    private async Task StartScan() => await JS.InvokeVoidAsync("QRScanner.start");
    private async Task StopScan() => await JS.InvokeVoidAsync("QRScanner.stop");

[JSInvokable]
public async Task OnQrDetected(string code)
{
    scanResult = code;
    StateHasChanged();

    // QR-Code bereinigen (falls Leerzeichen oder Zeilenumbrüche drin sind)
    string qrCode = code.Trim();

    if (string.IsNullOrEmpty(qrCode))
    {
        await JS.InvokeVoidAsync("showToast", "Ungültiger QR-Code", "error");
        return;
    }

    try
    {
        // Suche in Offline-DB nach Filter mit diesem QR-Code
        var filter = await FilterService.GetFilterByQrCodeAsync(qrCode);

        if (filter != null)
        {
            await JS.InvokeVoidAsync("showToast", $"Filter gefunden: {filter.Bezeichnung}", "success");

            // Stoppe Kamera sofort
            await StopScan();

            // Navigiere direkt zur Bearbeitung – mit allen nötigen IDs
            Nav.NavigateTo($"/filterform?filterId={filter.Id}&customerId={filter.CustomerId}&stationId={filter.StationId}");
        }
        else
        {
            await JS.InvokeVoidAsync("showToast", $"QR-Code '{qrCode}' nicht in Offline-Daten gefunden", "warning");
        }
    }
    catch (Exception ex)
    {
        await JS.InvokeVoidAsync("showToast", "Fehler beim Suchen des Filters", "error");
        Console.WriteLine(ex);
    }
}
}
