@page "/tracks/sessions"
@inherits CmsMediumBrowserBase<CmsSessionBrowser.SessionRow>
@using DeepDrftModels.DTOs
@using DeepDrftModels.Enums
@using Microsoft.AspNetCore.Components.Forms
@attribute [Authorize]
@inject ILogger<CmsSessionBrowser> Logger

<PageTitle>Sessions — DeepDrft CMS</PageTitle>

<MudContainer MaxWidth="MaxWidth.Large" Class="mt-8">
    <MudButton Variant="Variant.Text"
               StartIcon="@Icons.Material.Filled.ArrowBack"
               Href="/tracks/archive"
               Class="mb-4">
        Back to Release Archive
    </MudButton>

    <MudText Typo="Typo.h4" GutterBottom="true">Sessions</MudText>

    <CmsMediumTable TRow="SessionRow"
                    Rows="Rows"
                    Loading="Loading"
                    ReleaseAccessor="@(row => row.Release)"
                    ThumbUrl="@(key => ThumbUrl(key))"
                    TitleHeader="Session"
                    EmptyMessage="No sessions found.">
        <ActionContent Context="row">
            @if (row.HeroImageEntryKey is { Length: > 0 } heroKey)
            {
                <div class="cms-album-thumb" style="background-image: url('@ThumbUrl(heroKey)');"></div>
            }
            else
            {
                <div class="cms-album-thumb cms-album-thumb--fallback"></div>
            }
            <MudFileUpload T="IBrowserFile"
                           Accept="image/*"
                           FilesChanged="@(file => UploadHeroAsync(row, file))"
                           Disabled="@row.IsUploading">
                <ActivatorContent>
                    <MudButton Variant="Variant.Outlined"
                               Size="Size.Small"
                               StartIcon="@Icons.Material.Filled.Image"
                               Disabled="@row.IsUploading">
                        @if (row.IsUploading)
                        {
                            <MudProgressCircular Class="mr-2" Size="Size.Small" Indeterminate="true" />
                            <span>Uploading…</span>
                        }
                        else
                        {
                            <span>@(row.HeroImageEntryKey is { Length: > 0 } ? "Replace hero" : "Set hero")</span>
                        }
                    </MudButton>
                </ActivatorContent>
            </MudFileUpload>
        </ActionContent>
    </CmsMediumTable>
</MudContainer>

@code {
    protected override ReleaseMedium Medium => ReleaseMedium.Session;
    protected override string MediumNoun => "sessions";

    protected override SessionRow ToRow(ReleaseDto release) => new()
    {
        Release = release,
        HeroImageEntryKey = release.SessionMetadata?.HeroImageEntryKey
    };

    private async Task UploadHeroAsync(SessionRow row, IBrowserFile? file)
    {
        if (file is null) return;
        row.IsUploading = true;
        StateHasChanged();
        try
        {
            await using var stream = file.OpenReadStream(maxAllowedSize: 50_000_000);
            var result = await CmsReleaseService.UploadSessionHeroImageAsync(
                row.Release.Id, stream, file.Name, file.ContentType);

            if (result.Success)
            {
                // The endpoint returns no payload; the entry key is server-generated. Re-fetch the
                // release so the hero thumbnail reflects the new key without guessing it.
                var refreshed = await CmsReleaseService.GetByIdAsync(row.Release.Id);
                if (refreshed.Success && refreshed.Value is { } release)
                {
                    row.Release = release;
                    row.HeroImageEntryKey = release.SessionMetadata?.HeroImageEntryKey;
                }
                Snackbar.Add($"Hero image set for '{row.Release.Title}'.", Severity.Success);
            }
            else
            {
                var error = result.Messages.FirstOrDefault()?.Message ?? "Unknown error";
                Snackbar.Add($"Hero image upload failed: {error}", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Hero image upload failed for release {ReleaseId}", row.Release.Id);
            Snackbar.Add("Hero image upload failed — please try again.", Severity.Error);
        }
        finally
        {
            row.IsUploading = false;
            StateHasChanged();
        }
    }

    public sealed class SessionRow
    {
        public required ReleaseDto Release { get; set; }
        public string? HeroImageEntryKey { get; set; }
        public bool IsUploading { get; set; }
    }
}
