using UnityEngine;
using TMPro;
using System.Threading.Tasks;

public class CoinWalletUIManager : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI[] walletTexts;
    
    // Performance: prevent repeated initialization and refresh spam
    private bool hasInitialized = false;
    private bool isRefreshing = false;
    private float lastRefreshTime = 0f;
    private const float REFRESH_COOLDOWN = 5f; // Minimum seconds between refreshes

    private void Awake()
    {
        // IMPORTANT: Only use explicitly assigned walletTexts from Inspector
        // Do NOT use GetComponentsInChildren as it will grab ALL text components!
        if (walletTexts == null || walletTexts.Length == 0)
        {
#if UNITY_EDITOR
            Debug.LogWarning("[CoinWalletUIManager] No walletTexts assigned in Inspector. Please assign the coin balance TextMeshProUGUI references manually.");
#endif
            // Don't fallback to GetComponentsInChildren - that corrupts other UI text!
        }
    }

    private async void Start()
    {
        // Skip if no wallet texts are assigned
        if (walletTexts == null || walletTexts.Length == 0)
        {
#if UNITY_EDITOR
            Debug.LogWarning("[CoinWalletUIManager] Skipping wallet initialization - no walletTexts assigned.");
#endif
            return;
        }

        await InitializeWalletAsync();
    }

    private async Task InitializeWalletAsync()
    {
        if (hasInitialized) return;
        
        int maxAttempts = 5; // Reduced from 10
        int currentAttempt = 0;
        float delayBetweenAttempts = 0.5f;

        while (currentAttempt < maxAttempts)
        {
            if (CoinWalletSystem.Instance != null && CoinWalletSystem.Instance.IsInitialized())
            {
                UpdateAllWallets(CoinWalletSystem.Instance.GetCurrentBalance());
                hasInitialized = true;
                return;
            }

#if UNITY_EDITOR
            Debug.Log($"[CoinWalletUIManager] Waiting for wallet system... Attempt {currentAttempt + 1}/{maxAttempts}");
#endif
            await Task.Delay((int)(delayBetweenAttempts * 1000));
            currentAttempt++;
        }

#if UNITY_EDITOR
        Debug.LogWarning("[CoinWalletUIManager] CoinWalletSystem initialization timed out");
#endif
    }

    public void UpdateAllWallets(int amount)
    {
        if (walletTexts == null) return;

        foreach (var walletText in walletTexts)
        {
            if (walletText != null)
            {
                walletText.text = amount.ToString();
            }
        }
    }

    public async void RefreshWalletUI()
    {
        // Skip if no wallet texts or if already refreshing
        if (walletTexts == null || walletTexts.Length == 0) return;
        if (isRefreshing) return;
        
        // Cooldown to prevent refresh spam
        if (Time.time - lastRefreshTime < REFRESH_COOLDOWN) return;
        
        isRefreshing = true;
        lastRefreshTime = Time.time;

#if UNITY_EDITOR
        Debug.Log("[CoinWalletUIManager] Refreshing wallet UI...");
#endif

        if (CoinWalletSystem.Instance != null)
        {
            await CoinWalletSystem.Instance.InitializeWallet();
            UpdateAllWallets(CoinWalletSystem.Instance.GetCurrentBalance());
        }
        
        isRefreshing = false;
    }

    private void OnEnable()
    {
        // Only refresh if already initialized and cooldown passed
        // This prevents spam when toggling between screens
        if (hasInitialized && Time.time - lastRefreshTime >= REFRESH_COOLDOWN)
        {
            RefreshWalletUI();
        }
    }
}
