@page "/filterform"
@inject IJSRuntime JS
@using FilterCair.Shared.Models
@using Microsoft.AspNetCore.Components.Forms

<PageTitle>Filterdaten erfassen</PageTitle>

<div class="container py-4 fade-in">
    <div class="card shadow-sm border-0 rounded-4">
        <div class="card-body p-4">

            <h4 class="mb-4 text-center text-primary">
                <i class="bi bi-funnel me-2"></i> Filterdaten erfassen
            </h4>

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

                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-semibold">Filter-ID</label>
                        <InputText class="form-control form-control-lg" @bind-Value="filter.FilterId" placeholder="z. B. FC-A-234" />
                    </div>

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

                    <div class="col-md-6">
                        <label class="form-label fw-semibold">Zustand</label>
                        <InputSelect class="form-select form-select-lg" @bind-Value="filter.Zustand">
                            <option value="">– bitte wählen –</option>
                            <option>In Ordnung</option>
                            <option>Verschmutzt</option>
                            <option>Defekt</option>
                        </InputSelect>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label fw-semibold">Luftdruck (Pa)</label>
                        <InputNumber class="form-control form-control-lg" @bind-Value="filter.Luftdruck" />
                    </div>

                    <div class="col-12">
                        <label class="form-label fw-semibold">Bemerkung</label>
                        <InputTextArea class="form-control form-control-lg" rows="3" @bind-Value="filter.Bemerkung" />
                    </div>

                    <!-- 📸 Fotos hinzufügen -->
                    <div class="col-12">
                        <label class="form-label fw-semibold">Fotos anhängen</label>
                        <InputFile OnChange="OnFilesSelected" multiple class="form-control" />
                    </div>

                    @if (imagePreviews.Count > 0)
                    {
                        <div class="col-12 mt-3">
                            <div class="d-flex flex-wrap gap-3 justify-content-center">
                                @foreach (var img in imagePreviews)
                                {
                                    <div class="image-preview border rounded shadow-sm">
                                        <img src="@img" alt="Foto" class="img-thumbnail" />
                                    </div>
                                }
                            </div>
                        </div>
                    }
                </div>

                <div class="d-grid mt-4">
                    <button type="submit" class="btn btn-primary btn-lg rounded-pill shadow-sm">
                        <i class="bi bi-save me-2"></i> Speichern
                    </button>
                </div>
            </EditForm>

            @if (showToast)
            {
                <div class="toast-container position-fixed bottom-0 end-0 p-3">
                    <div class="toast align-items-center text-bg-success border-0 show fade-in-toast">
                        <div class="d-flex">
                            <div class="toast-body">
                                ✅ Filterdaten erfolgreich gespeichert!
                            </div>
                        </div>
                    </div>
                </div>
            }
        </div>
    </div>
</div>

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

    private async Task OnFilesSelected(InputFileChangeEventArgs e)
    {
        imagePreviews.Clear();

        foreach (var file in e.GetMultipleFiles(3)) // max. 3 Bilder
        {
            using var stream = file.OpenReadStream(maxAllowedSize: 5_000_000); // 5 MB max
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            var base64 = Convert.ToBase64String(ms.ToArray());
            imagePreviews.Add($"data:{file.ContentType};base64,{base64}");
        }

        StateHasChanged();
    }

    private async Task SaveForm()
    {
        Console.WriteLine($"Gespeichert: {System.Text.Json.JsonSerializer.Serialize(filter)}");
        await JS.InvokeVoidAsync("console.log", "Filter gespeichert:", filter);

        showToast = true;
        StateHasChanged();

        await Task.Delay(3000);
        showToast = false;
        StateHasChanged();
    }

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

    protected override void OnInitialized()
    {
        var qrParam = NavManager?.ToAbsoluteUri(NavManager.Uri).Query;
        if (!string.IsNullOrEmpty(qrParam))
        {
            var parts = System.Web.HttpUtility.ParseQueryString(qrParam);
            filter.FilterId = parts.Get("id");
        }
    }
}
