@page "/group/{GroupId:guid}/applications"
@using GmRelay.Web.Services
@using GmRelay.Shared.Domain
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@inject AuthorizedMembershipService MembershipService
@inject AuthorizedSessionService SessionService
@inject NavigationManager Navigation
@inject IHttpContextAccessor HttpContextAccessor
@using System.Security.Claims

<PageTitle>Заявки участников — GM-Relay</PageTitle>

<div class="page-container">
    <ul class="gm-breadcrumb animate-fade-in">
        <li><a href="/">Главная</a></li>
        <li><a href="@($"/group/{GroupId}")">Группа</a></li>
        <li class="active">Заявки</li>
    </ul>

    <div class="page-header animate-fade-in">
        <h2>📨 Заявки участников</h2>
        <p>Одобряйте или отклоняйте заявки на участие в клубе.</p>
    </div>

    @if (accessDenied)
    {
        <div class="glass-card public-empty-state">
            <h2>Нет доступа</h2>
            <p>Только owner или co-GM группы могут просматривать заявки.</p>
        </div>
    }
    else if (applications is null)
    {
        <div class="glass-card" style="padding: 2rem;">
            <div class="skeleton skeleton-text" style="width: 70%; height: 2rem; margin-bottom: 1rem;"></div>
            <div class="skeleton skeleton-text" style="width: 90%;"></div>
        </div>
    }
    else if (applications.Count == 0)
    {
        <div class="glass-card public-empty-state">
            <h2>Новых заявок нет</h2>
            <p>Когда игроки подадут заявку на участие в клубе, она появится здесь.</p>
        </div>
    }
    else
    {
        <ul class="application-list">
            @foreach (var app in applications)
            {
                <li class="glass-card application-item">
                    <div class="application-info">
                        <strong>@app.DisplayName</strong>
                        <span class="status-badge status-neutral">@app.Platform</span>
                        @if (!string.IsNullOrWhiteSpace(app.ExternalUsername))
                        {
                            <span class="application-meta">@app.ExternalUsername</span>
                        }
                        <span class="application-meta">@app.AppliedAt.ToString("dd.MM.yyyy HH:mm")</span>
                        @if (!string.IsNullOrWhiteSpace(app.Message))
                        {
                            <p class="application-message">«@app.Message»</p>
                        }
                    </div>
                    <div class="application-actions">
                        <button type="button" class="btn-gm btn-gm-success" disabled="@(busyMembershipId is not null)" @onclick="() => Approve(app.MembershipId)">
                            ✅ Одобрить
                        </button>
                        <button type="button" class="btn-gm btn-gm-outline" disabled="@(busyMembershipId is not null)" @onclick="() => Reject(app.MembershipId)">
                            ❌ Отклонить
                        </button>
                    </div>
                </li>
            }
        </ul>
    }

    @if (!string.IsNullOrEmpty(errorMessage))
    {
        <div class="gm-alert gm-alert-danger" style="margin-top: 1rem;">⚠️ @errorMessage</div>
    }
</div>

@code {
    [Parameter] public Guid GroupId { get; set; }

    private List<WebPendingApplication>? applications;
    private bool accessDenied;
    private string? errorMessage;
    private Guid? busyMembershipId;

    protected override async Task OnParametersSetAsync()
    {
        accessDenied = false;
        try
        {
            applications = await MembershipService.GetPendingApplicationsAsync(GroupId);
        }
        catch (SessionAccessDeniedException)
        {
            accessDenied = true;
        }
    }

    private async Task Approve(Guid membershipId)
    {
        errorMessage = null;
        busyMembershipId = membershipId;
        try
        {
            await MembershipService.ApproveForCurrentGmAsync(membershipId);
            applications = await MembershipService.GetPendingApplicationsAsync(GroupId);
        }
        catch (SessionAccessDeniedException)
        {
            accessDenied = true;
        }
        catch (InvalidOperationException ex)
        {
            errorMessage = ex.Message;
        }
        finally
        {
            busyMembershipId = null;
        }
    }

    private async Task Reject(Guid membershipId)
    {
        errorMessage = null;
        busyMembershipId = membershipId;
        try
        {
            await MembershipService.RejectForCurrentGmAsync(membershipId);
            applications = await MembershipService.GetPendingApplicationsAsync(GroupId);
        }
        catch (SessionAccessDeniedException)
        {
            accessDenied = true;
        }
        catch (InvalidOperationException ex)
        {
            errorMessage = ex.Message;
        }
        finally
        {
            busyMembershipId = null;
        }
    }
}
