@page "/PrivateList"
@rendermode InteractiveServer

@using Microsoft.AspNetCore.Authorization
@using CouchLog.Data
@using Microsoft.AspNetCore.Identity
@using Microsoft.EntityFrameworkCore

@inject ApplicationDbContext CouchLogDB
@inject UserManager<ApplicationUser> UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager

@attribute [Authorize]

<PageTitle>Private List</PageTitle>

<div class="container-fluid mt-4 px-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Private List</h2>
    </div>

    <!-- Grid-Layout -->
    <div class="row g-4">
        @foreach (var Entity in PrivateEntities)
        {
            /*
            Hier bleiben wir bei col-lg-6 (halbe Bildschirmbreite),
            wie du es im roten Kasten wolltest.
            */
            <div class="col-12 col-lg-6 col-xxl-4">

                <div class="card shadow-sm border-0 overflow-hidden private-entity-card">
                    <div class="row g-0 h-100">

                        <!-- BILD: col-auto sorgt dafür, dass sich die Breite nach CSS richtet -->
                        <div class="col-auto img-wrapper">
                            @if (!string.IsNullOrEmpty(Entity.GlobalEntity?.PicturePath))
                            {
                                <img src="@Entity.GlobalEntity.PicturePath"
                                     class="entity-img"
                                     alt="@Entity.GlobalEntity.Title">
                            }
                            else
                            {
                                <div class="d-flex align-items-center justify-content-center h-100 bg-light text-muted small px-2">
                                    Kein Bild
                                </div>
                            }
                        </div>

                        <!-- INFO: 'col' nimmt automatisch den RESTLICHEN Platz ein -->
                        <div class="col">
                            <div class="card-body d-flex flex-column h-100 py-2 px-3">

                                <!-- Header -->
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="overflow-hidden">
                                        <h5 class="card-title fw-bold mb-0 text-truncate">@Entity.GlobalEntity?.Title</h5>
                                        <small class="text-muted meta-text">
                                            @Entity.CreationTime.ToShortDateString()
                                        </small>
                                    </div>

                                    <div class="dropdown ms-1">
                                        <button class="btn btn-link menu-btn" type="button" data-bs-toggle="modal" data-bs-target="#modal-@Entity.Id">
                                            &#8942;
                                        </button>
                                    </div>
                                </div>

                                <select class="form-select"
                                        value="@Entity.UserWatchStatusId"
                                        @onchange="@(e => UpdateWatchStatus(Entity, e.Value))">

                                    @foreach (var status in userWatchStatuses)
                                    {
                                        <option value="@status.Id">@status.Name</option>
                                    }
                                </select>

                                @if (Entity.GlobalEntity?.MediaType.Name == "Series")
                                {
                                    <select class="form-select" value="@Entity.Season" @onchange="@(e => UpdateSeason(Entity, e.Value))">
                                        @{
                                            int currentSeason = Entity.Season ?? 1;

                                            int startOffsetSeason = currentSeason > 1 ? -1 : 0;
                                        }

                                        @for (int i = startOffsetSeason; i <= 5; i++)
                                        {
                                            int season = currentSeason + i;

                                            <option value="@season">
                                                Staffel @season
                                            </option>
                                        }
                                    </select>

                                    <select class="form-select" value="@Entity.Episode" @onchange="@(e => UpdateEpisode(Entity, e.Value))">
                                        @{
                                            int currentEpisode = Entity.Episode ?? 1;

                                            int startOffsetEpisode = currentEpisode > 1 ? -1 : 0;
                                        }

                                        @for (int i = startOffsetEpisode; i <= 5; i++)
                                        {
                                            int episode = currentEpisode + i;

                                            <option value="@episode">
                                                Episode @episode
                                            </option>
                                        }
                                    </select>
                                }

                                <!-- Beschreibung -->
                                <!--<p class="card-text text-truncate-multiline flex-grow-1 text-muted small mt-1 mb-2">
                                    @(!string.IsNullOrWhiteSpace(Entity.Description)
                                                                    ? Entity.Description
                                                                    : (Entity.Description ?? "Keine Beschreibung."))
                                </p>
                                -->
                                <!-- Footer Button -->
                                <div class="mt-auto d-flex justify-content-end">
                                    <button class="btn btn-outline-secondary btn-sm btn-details" type="button">Details</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Modal (unverändert) -->
                <div class="modal fade" id="modal-@Entity.Id" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Optionen</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">Optionen...</div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Schließen</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        }
    </div>
</div>

@code
{
    private List<PrivateEntity> PrivateEntities = new List<PrivateEntity>();
    private List<UserWatchStatus> userWatchStatuses = new List<UserWatchStatus>();
    ApplicationUser? AppUser = new();

    protected override async Task OnInitializedAsync()
    {
        var AuthState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        AppUser = await UserManager.GetUserAsync(AuthState.User);

        if (AppUser != null)
        {
            PrivateEntities = await CouchLogDB.PrivateEntities
                .Where(x => x.UserId == AppUser.Id)
                .Include(x => x.GlobalEntity)
                .Include(x => x.UserWatchStatus)
                .Include(x => x.GlobalEntity.MediaType)
                .OrderByDescending(Entity => Entity.LastChange ?? Entity.CreationTime)
                .ToListAsync();

            userWatchStatuses = await CouchLogDB.UserWatchStatuses.OrderByDescending(Entity => Entity.Id).ToListAsync();
        }
    }

    private async Task UpdateWatchStatus(PrivateEntity entity, object? newValue)
    {
        // Wir holen uns die gewählte ID aus dem Dropdown
        if (int.TryParse(newValue?.ToString(), out int newId))
        {
            // 1. ID im Objekt aktualisieren
            entity.UserWatchStatusId = newId;

            // 2. Navigation Property aktualisieren (damit die UI nicht flackert)
            // Wir suchen das passende Objekt aus der geladenen Liste
            entity.UserWatchStatus = userWatchStatuses.FirstOrDefault(s => s.Id == newId);

            // 3. Ab in die Datenbank
            await CouchLogDB.SaveChangesAsync();
        }
    }

    private async Task UpdateSeason(PrivateEntity entity, object? newSeasonValue)
    {
        if(int.TryParse(newSeasonValue?.ToString(), out int newSeason))
        {
            entity.Season = newSeason;

            await CouchLogDB.SaveChangesAsync();
        }
    }

    private async Task UpdateEpisode(PrivateEntity entity, object? newEpisodeValue)
    {
        if (int.TryParse(newEpisodeValue?.ToString(), out int newEpisode))
        {
            entity.Episode = newEpisode;

            await CouchLogDB.SaveChangesAsync();
        }
    }
}