@page "/filterform"
@inject IJSRuntime JS

@using FilterCair.Shared.Models

<PageTitle>Filterdaten erfassen</PageTitle>

<div class="container py-4">
    <h4 class="mb-4 text-center">Filterdaten erfassen</h4>

    <EditForm Model="@filter" OnValidSubmit="SaveForm">
        <DataAnnotationsValidator />
        <ValidationSummary />

        <div class="mb-3">
            <label class="form-label">Filter-ID</label>
            <InputText class="form-control" @bind-Value="filter.FilterId" placeholder="z. B. FC-A-234" />
        </div>

        <div class="mb-3">
            <label class="form-label">Halle</label>
            <InputSelect class="form-select" @bind-Value="filter.Halle">
                <option value="">– bitte wählen –</option>
                @foreach (var h in halls)
                {
                    <option value="@h">@h</option>
                }
            </InputSelect>
        </div>

        <div class="mb-3">
            <label class="form-label">Zustand</label>
            <InputSelect class="form-select" @bind-Value="filter.Zustand">
                <option value="">– bitte wählen –</option>
                <option>In Ordnung</option>
                <option>Verschmutzt</option>
                <option>Defekt</option>
            </InputSelect>
        </div>

        <div class="mb-3">
            <label class="form-label">Luftdruck (Pa)</label>
            <InputNumber class="form-control" @bind-Value="filter.Luftdruck" />
        </div>

        <div class="mb-3">
            <label class="form-label">Bemerkung</label>
            <InputTextArea class="form-control" rows="3" @bind-Value="filter.Bemerkung" />
        </div>

        <button type="submit" class="btn btn-success w-100">
            Speichern
        </button>
    </EditForm>

    @if (saved)
    {
        <div class="alert alert-success mt-4 text-center">
            Daten gespeichert!
        </div>
    }
</div>

@code {
    private FilterModel filter = new();
    private bool saved = false;
    private List<string> halls = new() { "Halle A", "Halle B", "Halle C" };

    private async Task SaveForm()
    {
        saved = true;
        Console.WriteLine($"Gespeichert: {System.Text.Json.JsonSerializer.Serialize(filter)}");

        // später → JS.InvokeVoidAsync("IndexedDB.saveFilter", filter);
        await JS.InvokeVoidAsync("console.log", "Filter gespeichert:", filter);
    }

    // optional: QR-Ergebnis vorbelegen
    protected override void OnInitialized()
    {
        var qrParam = NavManager?.ToAbsoluteUri(NavManager.Uri).Query;
        if (!string.IsNullOrEmpty(qrParam))
        {
            // z. B. ?id=FC-123
            var parts = System.Web.HttpUtility.ParseQueryString(qrParam);
            filter.FilterId = parts.Get("id");
        }
    }

    [Inject] NavigationManager? NavManager { get; set; }
}
