@page "/"
@using Microsoft.AspNetCore.Components.Authorization
@using web.PixelTalk.Models
@using web.PixelTalk.Services
@using MongoDB.Driver
@inject AuthenticationStateProvider AuthStateProvider
@inject MongoService MongoService

<PageTitle>PixelTalk Dashboard</PageTitle>

<AuthorizeView>
    <Authorized>
        <div class="container mt-4">
            <h1 class="mb-4">Welcome, @player?.Nickname!</h1>
            <div class="row">
                <div class="col-md-4 mb-3">
                    <div class="card shadow-sm text-center">
                        <div class="card-body">
                            <h5 class="card-title text-muted">Current Points</h5>
                            <h2 class="display-4 text-success">@player?.Points.ToString("N0")</h2>
                        </div>
                    </div>
                </div>
            </div>

            <h3 class="mt-5 mb-3">Rewards Store</h3>
            @if (message != null)
            {
                <div class="alert alert-info" role="alert">@message</div>
            }
            <div class="row">
                @foreach (var item in storeItems)
                {
                    <div class="col-md-4 mb-4">
                        <div class="card shadow-sm h-100">
                            <div class="card-body d-flex flex-column">
                                <h5 class="card-title">@item.Name</h5>
                                <p class="card-text flex-grow-1">@item.Description</p>
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <span class="badge bg-primary fs-6">@item.Cost.ToString("N0") pts</span>
                                    <button class="btn btn-sm btn-outline-success" @onclick="() => BuyItem(item)" disabled="@(player?.Points < item.Cost)">
                                        Purchase
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                }
            </div>
        </div>
    </Authorized>
    <NotAuthorized>
        <div class="container text-center mt-5">
            <h1 class="display-5">Welcome to PixelTalk</h1>
            <p class="lead mt-3 text-muted">You are not authenticated. Please log in utilizing our in-game system to view your dashboard.</p>
            <a href="/auth" class="btn btn-primary btn-lg mt-4 shadow-sm">Authenticate via Game</a>
        </div>
    </NotAuthorized>
</AuthorizeView>

@code {
    private PlayerData? player;
    private List<StoreItem> storeItems = new();
    private string? message;

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        if (user.Identity?.IsAuthenticated ?? false)
        {
            var uuid = user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
            if (uuid != null)
            {
                player = await MongoService.Players.Find(p => p.Uuid == uuid).FirstOrDefaultAsync();
                storeItems = await MongoService.StoreItems.Find(_ => true).ToListAsync();
            }
        }
    }

    private async Task BuyItem(StoreItem item)
    {
        message = null;
        if (player == null || player.Points < item.Cost) return;

        bool success = await MongoService.DeductPointsAsync(player.Uuid, item.Cost);
        if (success)
        {
            player.Points -= item.Cost;
            
            var log = new PurchaseLog
            {
                Uuid = player.Uuid,
                ItemId = item.Id,
                ItemName = item.Name,
                Cost = item.Cost,
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };
            await MongoService.PurchaseLogs.InsertOneAsync(log);

            message = $"Successfully purchased {item.Name} for {item.Cost} points!";
        }
        else
        {
            message = "Transaction failed. Insufficient points or an error occurred!";
        }
        StateHasChanged();
    }
}
