using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using Google.Impl;
using MS;
using TMPro; // Required for TextMeshPro
using System;
public class Top10RankChecker : MonoBehaviour
{
    public static Top10RankChecker Instance { get; private set; }

    public Popup top10Panel;
    public LeaderboardType leaderboardType = LeaderboardType.PiPuzzle;
    public TextMeshProUGUI timeSpentText; 
    public TextMeshProUGUI DifficultyText; 

    private const string LastRankKey = "LastKnownRank";
    private const string LevelTimeKey = "LastLevelTimeSpent";

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
        DontDestroyOnLoad(gameObject);
    }

    private void Start()
    {
        //CheckMyRank();
    }

    public void CheckMyRank()
    {
        string statName = leaderboardType.GetStatisticName();

        var request = new GetLeaderboardAroundPlayerRequest
        {
            StatisticName = statName,
            MaxResultsCount = 1
        };

        PlayFabClientAPI.GetLeaderboardAroundPlayer(request, result =>
        {
            if (result.Leaderboard != null && result.Leaderboard.Count > 0)
            {
                int currentRank = result.Leaderboard[0].Position;
                int lastRank = PlayerPrefs.GetInt(LastRankKey, 999);

                Debug.Log($"Current Rank: {currentRank}, Last Rank: {lastRank}");

                if (lastRank > 9 && currentRank <= 9)
                {
                    ShowTimeSpent();
                    ShowDifficultylevel();
                    top10Panel.Open();
                    Debug.Log("🎉 Entered Top 10! Showing panel.");
                }

                PlayerPrefs.SetInt(LastRankKey, currentRank);
                PlayerPrefs.Save();
            }
        }, error =>
        {
            Debug.LogError("Failed to fetch leaderboard around player: " + error.GenerateErrorReport());
        });
    }
    public void CheckMyRank(string statisticsName)
    {
        string statName = statisticsName;

        var request = new GetLeaderboardAroundPlayerRequest
        {
            StatisticName = statName,
            MaxResultsCount = 10
        };

        PlayFabClientAPI.GetLeaderboardAroundPlayer(request, result =>
        {
            if (result.Leaderboard != null && result.Leaderboard.Count > 0)
            {
                int currentRank = result.Leaderboard[0].Position;
                int lastRank = PlayerPrefs.GetInt(LastRankKey, 999);

                Debug.Log($"Current Rank: {currentRank}, Last Rank: {lastRank}");

                if (lastRank > 9 && currentRank <= 9)
                {
                    ShowTimeSpent();
                    ShowDifficultylevel();
                    top10Panel.Open();
                    Debug.Log("🎉 Entered Top 10! Showing panel.");
                }

                PlayerPrefs.SetInt(LastRankKey, currentRank);
                PlayerPrefs.Save();
            }
        }, error =>
        {
            Debug.LogError("Failed to fetch leaderboard around player: " + error.GenerateErrorReport());
        });
    }
     private void ShowTimeSpent()
    {
        float rawSeconds = PlayerPrefs.GetFloat(LevelTimeKey, 0f);
        int minutes = Mathf.FloorToInt(rawSeconds / 60f);
        int seconds = Mathf.FloorToInt(rawSeconds % 60f);

        string formattedTime = $"{minutes}m and {seconds}s";

        if (timeSpentText != null)
            timeSpentText.text = formattedTime;
        else
            Debug.LogWarning("timeSpentText is not assigned in Top10RankChecker");
    }
    void ShowDifficultylevel()
    {
        DifficultyText.text = GameManager.currentLevelGroup.LevelGroupName;
    }    
}