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

[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 recordText;

    [SerializeField]
    private TMP_Text vpipText;

    [SerializeField]
    private TMP_Text pfrText;

    [SerializeField]
    private TMP_Text threeBetText;

    [SerializeField]
    private TMP_Text foldToThreeBetText;

    [SerializeField]
    private TMP_Text cBetText;

    [SerializeField]
    private TMP_Text foldToCBetText;

    [SerializeField]
    private TMP_Text biggestWinText;

    [SerializeField]
    private TMP_Text bestHandNameText;

    // Five slots showing the biggest-win hand, drawn from card_atlas (13 columns 2..A, 4 rows).
    [SerializeField]
    private RawImage[] bestHandCards;

    // Same five slots, drawn behind the cards with the outline material; lit for the hole cards in the hand.
    [SerializeField]
    private RawImage[] bestHandHighlights;

    // Card ids run diamonds, hearts, clubs, spades, which is also the atlas row order from the top.

    [SerializeField]
    private TMP_Text perHandText;

    [SerializeField]
    private TMP_Text hatsText;

    // 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.IsReady())
        {
            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();
        }

        if (recordText != null)
        {
            recordText.text = wins + "/" + losses;
        }

        // Given/received
        if (donatedText != null)
        {
            donatedText.text = donated + "/" + balanceComponent.GetDonationsReceived();
        }

        // Playstyle
        int trackedHands = balanceComponent.GetTrackedHands();
        SetPercent(vpipText, trackedHands, balanceComponent.GetVPIPPercent());
        SetPercent(pfrText, trackedHands, balanceComponent.GetPFRPercent());
        SetPercent(threeBetText, balanceComponent.GetThreeBetOpportunities(), balanceComponent.GetThreeBetPercent());
        SetPercent(foldToThreeBetText, balanceComponent.GetFoldToThreeBetOpportunities(), balanceComponent.GetFoldToThreeBetPercent());
        SetPercent(cBetText, balanceComponent.GetCBetOpportunities(), balanceComponent.GetCBetPercent());
        SetPercent(foldToCBetText, balanceComponent.GetFoldToCBetOpportunities(), balanceComponent.GetFoldToCBetPercent());

        // Rare 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 (perHandText != null)
        {
            int handsPlayed = balanceComponent.GetHandsPlayed();
            perHandText.text = handsPlayed > 0
                ? Mathf.RoundToInt((float)balanceComponent.GetProfit() / handsPlayed).ToString("+#,0;-#,0;0")
                : "-";
        }
        if (hatsText != null)
        {
            hatsText.text = balanceComponent.GetHatsGiven() + "/" + balanceComponent.GetHatsReceived();
        }

        UpdateBestHand();
    }

    private void SetPercent(TMP_Text label, int samples, float percent)
    {
        if (label == null) return;
        label.text = samples > 0 ? Mathf.RoundToInt(percent).ToString() + "%" : "-";
    }

    private void UpdateBestHand()
    {
        int amount = balanceComponent.GetBiggestWin();
        int packed = balanceComponent.GetBiggestWinHand();
        if (amount <= 0)
        {
            ClearBestHand();
            return;
        }

        if (biggestWinText != null)
        {
            biggestWinText.text = "+" + amount.ToString();
        }

        // The amount stands on its own; only draw cards we can vouch for
        int[] cards = HoldemHandEvaluator.UnpackBestFive(packed);
        if ((packed & 0x3FFFFFFF) == 0 || !AreFiveDistinctCards(cards))
        {
            HideBestHandCards();
            if (bestHandNameText != null)
            {
                bestHandNameText.text = "-";
            }
            return;
        }

        // Hole cards are the first cards in packed order; the sort below moves them, so remember them by id
        int holeCount = HoldemHandEvaluator.UnpackHoleCount(packed);
        int hole0 = holeCount > 0 ? cards[0] : -1;
        int hole1 = holeCount > 1 ? cards[1] : -1;

        ulong value = HoldemHandEvaluator.EvaluateHand(cards[0], cards[1], cards[2], cards[3], cards[4]);
        SortBestHand(cards, value);
        for (int i = 0; i < 5; ++i)
        {
            SetCardSlot(i, cards[i], cards[i] == hole0 || cards[i] == hole1);
        }

        if (bestHandNameText != null)
        {
            bestHandNameText.text = HoldemHandEvaluator.HandClass(value);
        }
    }

    // Packed order follows the deal, so put the cards that make the hand first:
    // most repeated rank first, then highest rank. The ace plays low in a wheel straight.
    private void SortBestHand(int[] cards, ulong value)
    {
        int handClass = HoldemHandEvaluator.GetHandClassInt(value);
        bool hasAce = false;
        bool hasTwo = false;
        for (int i = 0; i < 5; ++i)
        {
            if (cards[i] % 13 == 12) hasAce = true;
            if (cards[i] % 13 == 0) hasTwo = true;
        }
        bool wheel = (handClass == 4 || handClass == 8) && hasAce && hasTwo;

        int[] scores = new int[5];
        for (int i = 0; i < 5; ++i)
        {
            int rank = cards[i] % 13;
            int count = 0;
            for (int j = 0; j < 5; ++j)
            {
                if (cards[j] % 13 == rank) count++;
            }
            scores[i] = count * 100 + ((wheel && rank == 12) ? -1 : rank);
        }

        // insertion sort, descending
        for (int i = 1; i < 5; ++i)
        {
            int card = cards[i];
            int score = scores[i];
            int j = i - 1;
            while (j >= 0 && scores[j] < score)
            {
                cards[j + 1] = cards[j];
                scores[j + 1] = scores[j];
                j--;
            }
            cards[j + 1] = card;
            scores[j + 1] = score;
        }
    }

    private void SetCardSlot(int slot, int cardId, bool isHole)
    {
        if (bestHandCards == null || slot >= bestHandCards.Length) return;
        RawImage image = bestHandCards[slot];
        if (image == null) return;

        int rank = cardId % 13;
        int row = cardId / 13;
        Rect uv = new Rect(rank / 13f, (3 - row) / 4f, 1f / 13f, 0.25f);
        // Enable before assigning so the mesh is rebuilt with the rect once the graphic is active
        image.enabled = true;
        image.uvRect = uv;
        // The card front comes from the shared card material, which the deck picker swaps at runtime
        image.SetMaterialDirty();

        if (bestHandHighlights == null || slot >= bestHandHighlights.Length) return;
        RawImage glow = bestHandHighlights[slot];
        if (glow == null) return;
        // Only the card outline is used, which is the same in every cell, so the glow keeps its prefab UV
        glow.enabled = isHole;
    }

    private void ClearBestHand()
    {
        if (biggestWinText != null)
        {
            biggestWinText.text = "-";
        }
        if (bestHandNameText != null)
        {
            bestHandNameText.text = "No wins yet";
        }
        HideBestHandCards();
    }

    private void HideBestHandCards()
    {
        if (bestHandCards == null) return;
        for (int i = 0; i < bestHandCards.Length; ++i)
        {
            if (bestHandCards[i] != null) bestHandCards[i].enabled = false;
        }
        if (bestHandHighlights == null) return;
        for (int i = 0; i < bestHandHighlights.Length; ++i)
        {
            if (bestHandHighlights[i] != null) bestHandHighlights[i].enabled = false;
        }
    }

    private bool AreFiveDistinctCards(int[] cards)
    {
        for (int i = 0; i < 5; ++i)
        {
            if (cards[i] < 0 || cards[i] > 51) return false;
            for (int j = 0; j < i; ++j)
            {
                if (cards[j] == cards[i]) return false;
            }
        }
        return true;
    }

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 (recordText != null)
        {
            recordText.text = "0/0";
        }
        if (donatedText != null)
        {
            donatedText.text = "0/0";
        }
        SetPercent(vpipText, 0, 0f);
        SetPercent(pfrText, 0, 0f);
        SetPercent(threeBetText, 0, 0f);
        SetPercent(foldToThreeBetText, 0, 0f);
        SetPercent(cBetText, 0, 0f);
        SetPercent(foldToCBetText, 0, 0f);
        if (fourOfAKindText != null)
        {
            fourOfAKindText.text = "0";
        }
        if (straightFlushText != null)
        {
            straightFlushText.text = "0";
        }
        if (royalFlushText != null)
        {
            royalFlushText.text = "0";
        }
        if (perHandText != null)
        {
            perHandText.text = "-";
        }
        if (hatsText != null)
        {
            hatsText.text = "0/0";
        }
        ClearBestHand();
    }

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