using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using PlayFab.ClientModels;
using PlayFab;
using System;
using System.Threading.Tasks;

public class StatsScreen : MonoBehaviour
{
    public TextMeshProUGUI levelsCompleted;
    public TextMeshProUGUI top10Count;
    public TextMeshProUGUI top3Count;
    public LevelGroup[] levelGroups;

    public int getAllTimerLevels()
    {
        int allLevels = 0;
        for (int i = 0; i < levelGroups.Length; i++)
        {
            allLevels += levelGroups[i].CompletedLevel_Timer;
        }
        return allLevels;
    }
    public async void OnScreenOpened()
    {
        levelsCompleted.text = getAllTimerLevels().ToString() + "/250";
        top10Count.text = "...";
        top3Count.text = "...";

        Task<int> top10Task = getAllTop10LevelsAsync();
        Task<int> top3Task = getAllTop3LevelsAsync();

        await Task.WhenAll(top10Task, top3Task);

        top10Count.text = top10Task.Result.ToString();
        top3Count.text = top3Task.Result.ToString();
    }
    private async Task<int> getAllTop3LevelsAsync()
    {
        int result = 0;
        int groupIndex = 0;

        foreach (var group in levelGroups)
        {
            for (int levelIndex = 0; levelIndex < group.CompletedLevel_Timer; levelIndex++)
            {
                string statisticName = $"{GameConstants.GameNamePrefix}_{groupIndex + 1}_Level_{levelIndex}_Time";

                if (await IsInTop3(statisticName))
                {
                    result++;
                }
            }

            groupIndex++;
        }

        return result;
    }

    private async Task<int> getAllTop10LevelsAsync()
    {
        int result = 0;
        int groupIndex = 0;

        foreach (var group in levelGroups)
        {
            for (int levelIndex = 0; levelIndex < group.CompletedLevel_Timer; levelIndex++)
            {
                string statisticName = $"{GameConstants.GameNamePrefix}_{groupIndex + 1}_Level_{levelIndex}_Time";

                if (await IsInTop10(statisticName))
                {
                    result++;
                }
            }

            groupIndex++;
        }

        return result;
    }

    public async Task<bool> IsInTop3(string statisticsName)
    {
        var request = new GetLeaderboardAroundPlayerRequest
        {
            StatisticName = statisticsName,
            MaxResultsCount = 10
        };

        var tcs = new TaskCompletionSource<bool>();

        PlayFabClientAPI.GetLeaderboardAroundPlayer(request, result =>
        {
            string myId = PlayFabSettings.staticPlayer.PlayFabId;
            var myEntry = result.Leaderboard.Find(entry => entry.PlayFabId == myId);
            tcs.SetResult(myEntry != null && myEntry.Position <= 2); // 0�2
        },
        error =>
        {
            Debug.LogError("Failed to fetch leaderboard: " + error.GenerateErrorReport());
            tcs.SetResult(false);
        });

        return await tcs.Task;
    }

    public async Task<bool> IsInTop10(string statisticsName)
    {
        var request = new GetLeaderboardAroundPlayerRequest
        {
            StatisticName = statisticsName,
            MaxResultsCount = 10
        };

        var tcs = new TaskCompletionSource<bool>();

        PlayFabClientAPI.GetLeaderboardAroundPlayer(request, result =>
        {
            string myId = PlayFabSettings.staticPlayer.PlayFabId;
            var myEntry = result.Leaderboard.Find(entry => entry.PlayFabId == myId);
            tcs.SetResult(myEntry != null && myEntry.Position <= 9); // 0�9
        },
        error =>
        {
            Debug.LogError("Failed to fetch leaderboard: " + error.GenerateErrorReport());
            tcs.SetResult(false);
        });

        return await tcs.Task;
    }
}