using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using VRC.SDK3.Persistence;
using TMPro;

[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class PanelBalance : UdonSharpBehaviour
{
    [SerializeField]
    private TMP_Text balanceText;

    [SerializeField]
    private TMP_Text totalWinLossText;

    [SerializeField]
    private TMP_Text winRateText;

    [SerializeField]
    private TMP_Text foldRateText;

    [SerializeField]
    private TMP_Text totalGamesText;

    [SerializeField]
    private TMP_Text donatedText;

    [SerializeField]
    private TMP_Text fourOfAKindText;

    [SerializeField]
    private TMP_Text straightFlushText;

    [SerializeField]
    private TMP_Text royalFlushText;

    [SerializeField]
    private TMP_Text pairText;

    // Cached reference to avoid repeated GetPlayerBalanceComponent calls
    private PlayerBalanceComponent balanceComponent;
    private bool isInitialized = false;

    void Start()
    {
        // Note: Initialization happens in OnPlayerRestored when player data is ready
    }

    private void InitializeComponent()
    {
        if (isInitialized) return;

        VRCPlayerApi localPlayer = Networking.LocalPlayer;
        if (localPlayer == null || !Utilities.IsValid(localPlayer))
        {
            // Will retry on next event
            return;
        }

        balanceComponent = PlayerBalanceComponent.GetPlayerBalanceComponent(localPlayer);
        if (balanceComponent == null)
        {
            // Will retry on next event
            return;
        }

        // Subscribe to balance change events instead of polling every frame
        balanceComponent.SubscribeToBalanceChanges(this);
        isInitialized = true;

        // Initial display update
        UpdateDisplay();
    }

    /// <summary>
    /// Called when PlayerData is updated for the local player.
    /// This is the VRChat-recommended way to react to persistence changes.
    /// </summary>
    public override void OnPlayerDataUpdated(VRCPlayerApi player, PlayerData.Info[] infos)
    {
        if (player != null && player.isLocal)
        {
            UpdateDisplay();
        }
    }

    /// <summary>
    /// Called by PlayerBalanceComponent when balance changes.
    /// This is more efficient than polling every frame.
    /// </summary>
    public void OnBalanceChanged()
    {
        UpdateDisplay();
    }

    /// <summary>
    /// Called when the player is restored (after joining/respawning).
    /// Good time to initialize cached references.
    /// </summary>
    public override void OnPlayerRestored(VRCPlayerApi player)
    {
        if (player != null && player.isLocal)
        {
            InitializeComponent();
            UpdateDisplay();
        }
    }

    private void UpdateDisplay()
    {
        // Lazy initialization if not done yet
        if (!isInitialized)
        {
            InitializeComponent();
        }

        if (balanceComponent == null)
        {
            SetDefaultDisplay();
            return;
        }

        if (!balanceComponent.IsBalanceReady())
        {
            SetDefaultDisplay();
            return;
        }

        // Update balance text
        if (balanceText != null)
        {
            int balance = balanceComponent.GetBalance();
            balanceText.text = balance >= 0 ? balance.ToString() : "-";
        }

        // Update total win/loss text
        if (totalWinLossText != null)
        {
            int profit = balanceComponent.GetProfit();
            if (profit > 0)
            {
                totalWinLossText.text = "+" + profit.ToString();
            }
            else
            {
                totalWinLossText.text = profit.ToString();
            }
        }

        // Get metrics
        int wins = balanceComponent.GetWins();
        int losses = balanceComponent.GetLosses();
        int folds = balanceComponent.GetFolds();
        int donated = balanceComponent.GetDonation();
        int totalGames = wins + losses + folds;
        int completedGames = wins + losses;

        // Update win rate text
        if (winRateText != null)
        {
            if (completedGames > 0)
            {
                float winRate = (float)wins / completedGames * 100f;
                winRateText.text = winRate.ToString("F2") + "%";
            }
            else
            {
                winRateText.text = "0.00%";
            }
        }

        // Update fold rate text
        if (foldRateText != null)
        {
            if (totalGames > 0)
            {
                float foldRate = (float)folds / totalGames * 100f;
                foldRateText.text = foldRate.ToString("F2") + "%";
            }
            else
            {
                foldRateText.text = "0.00%";
            }
        }

        // Update total games text
        if (totalGamesText != null)
        {
            totalGamesText.text = totalGames.ToString();
        }

        // Update donated text
        if (donatedText != null)
        {
            donatedText.text = donated.ToString();
        }

        // Update hand counts
        if (fourOfAKindText != null)
        {
            fourOfAKindText.text = balanceComponent.GetHandCount("FourOfAKind").ToString();
        }
        if (straightFlushText != null)
        {
            straightFlushText.text = balanceComponent.GetHandCount("StraightFlush").ToString();
        }
        if (royalFlushText != null)
        {
            royalFlushText.text = balanceComponent.GetHandCount("RoyalFlush").ToString();
        }
        if (pairText != null)
        {
            pairText.text = balanceComponent.GetHandCount("Pair").ToString();
        }
    }

    private void SetDefaultDisplay()
    {
        if (balanceText != null)
        {
            balanceText.text = "-";
        }
        if (totalWinLossText != null)
        {
            totalWinLossText.text = "0";
        }
        if (winRateText != null)
        {
            winRateText.text = "0.00%";
        }
        if (foldRateText != null)
        {
            foldRateText.text = "0.00%";
        }
        if (totalGamesText != null)
        {
            totalGamesText.text = "0";
        }
        if (donatedText != null)
        {
            donatedText.text = "0";
        }
        if (fourOfAKindText != null)
        {
            fourOfAKindText.text = "0";
        }
        if (straightFlushText != null)
        {
            straightFlushText.text = "0";
        }
        if (royalFlushText != null)
        {
            royalFlushText.text = "0";
        }
        if (pairText != null)
        {
            pairText.text = "0";
        }
    }

    void OnDestroy()
    {
        // Unsubscribe when destroyed to prevent memory leaks
        if (balanceComponent != null && isInitialized)
        {
            balanceComponent.UnsubscribeFromBalanceChanges(this);
        }
    }
}