@page "/wishlists"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@rendermode InteractiveServer
@inject IDbContextFactory<ApplicationDbContext> DbFactory
@inject AuthenticationStateProvider AuthState
@inject NavigationManager Nav

<PageTitle>My Wishlists</PageTitle>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h1>My Wishlists</h1>
    <button class="btn btn-primary" @onclick="StartCreate">+ New wishlist</button>
</div>

@if (creating)
{
    <div class="card mb-3">
        <div class="card-body">
            <EditForm Model="newList" OnValidSubmit="CreateAsync">
                <DataAnnotationsValidator />
                <div class="mb-2">
                    <label class="form-label">Title</label>
                    <InputText class="form-control" @bind-Value="newList.Title" />
                    <ValidationMessage For="() => newList.Title" />
                </div>
                <div class="mb-2">
                    <label class="form-label">Description (optional)</label>
                    <InputTextArea class="form-control" @bind-Value="newList.Description" rows="2" />
                </div>
                <button type="submit" class="btn btn-success btn-sm">Create</button>
                <button type="button" class="btn btn-link btn-sm" @onclick="() => creating = false">Cancel</button>
            </EditForm>
        </div>
    </div>
}

@if (owned is null)
{
    <p>Loading…</p>
}
else if (owned.Count == 0)
{
    <p class="text-secondary">You haven't created any wishlists yet.</p>
}
else
{
    <div class="list-group">
        @foreach (var w in owned)
        {
            <div class="list-group-item d-flex justify-content-between align-items-center">
                <a href="@($"wishlist/{w.Id}")" class="text-decoration-none flex-grow-1">
                    <strong>@w.Title</strong>
                    @if (w.IsArchived)
                    {
                        <span class="badge bg-secondary ms-2">Archived</span>
                    }
                    <span class="badge bg-light text-dark ms-2">@w.Items.Count items</span>
                    <div class="text-secondary small">@w.Description</div>
                </a>
                <button class="btn btn-outline-danger btn-sm" @onclick="() => DeleteAsync(w)">Delete</button>
            </div>
        }
    </div>
}

@code {
    private List<Wishlist>? owned;
    private bool creating;
    private NewListModel newList = new();

    protected override async Task OnInitializedAsync() => await LoadAsync();

    private async Task LoadAsync()
    {
        var userId = await AuthState.GetUserIdAsync();
        if (userId is null) return;
        await using var db = await DbFactory.CreateDbContextAsync();
        owned = await db.Wishlists
            .Include(w => w.Items)
            .Where(w => w.OwnerId == userId)
            .OrderByDescending(w => w.Id) // Id grows with creation; SQLite can't ORDER BY DateTimeOffset
            .ToListAsync();
    }

    private void StartCreate()
    {
        newList = new NewListModel();
        creating = true;
    }

    private async Task CreateAsync()
    {
        var userId = await AuthState.GetUserIdAsync();
        if (userId is null) return;
        await using var db = await DbFactory.CreateDbContextAsync();
        var w = new Wishlist { OwnerId = userId, Title = newList.Title.Trim(), Description = newList.Description };
        db.Wishlists.Add(w);
        await db.SaveChangesAsync();
        creating = false;
        Nav.NavigateTo($"wishlist/{w.Id}");
    }

    private async Task DeleteAsync(Wishlist w)
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        await db.Wishlists.Where(x => x.Id == w.Id).ExecuteDeleteAsync();
        await LoadAsync();
    }

    private sealed class NewListModel
    {
        [System.ComponentModel.DataAnnotations.Required, System.ComponentModel.DataAnnotations.MaxLength(200)]
        public string Title { get; set; } = "";
        public string? Description { get; set; }
    }
}
