using System;
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using VRC.SDK3.Persistence;
using VRC.SDK3.UdonNetworkCalling;
using VRC.Udon.Common.Interfaces;
using UCS;

[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class PlayerBalanceComponent : UdonSharpBehaviour
{
    public const string SaveKeyPrefix = "S1_";

    private int mockProfit = 0;

    // Reference to UdonChips for persistence
    public UdonChips udonChips;

    // Set on the master's copy so every charge it sends reaches the ledger
    [HideInInspector] public HoldemAuthority authority;

    // NETWORKED balance - this is what all players see
    // The master modifies this, and it syncs to all players
    [UdonSynced]
    public int CurrentSyncedBalance = -1;

    private bool bIsReady = false;

    // Periodic sync timer to ensure balance is synced reliably
    private float syncTimer = 0f;
    private const float SYNC_INTERVAL = 3f;

    // Event notification system for balance changes
    // Allows other components to subscribe instead of polling every frame
    private UdonSharpBehaviour[] balanceSubscribers = new UdonSharpBehaviour[10];
    private int subscriberCount = 0;

    //All balance-related functionality will do nothing if these return false.
    //These should also be checked before allowing a player to do anything that would need to read from/write to balance!
    public bool IsReady() { return bIsReady && CurrentSyncedBalance >= 0; }

    /// <summary>
    /// Subscribe to balance change notifications. The subscriber will receive OnBalanceChanged() events.
    /// This is more efficient than polling GetBalance() every frame.
    /// </summary>
    public void SubscribeToBalanceChanges(UdonSharpBehaviour subscriber)
    {
        if (subscriberCount < balanceSubscribers.Length)
        {
            balanceSubscribers[subscriberCount++] = subscriber;
        }
    }

    /// <summary>
    /// Unsubscribe from balance change notifications.
    /// </summary>
    public void UnsubscribeFromBalanceChanges(UdonSharpBehaviour subscriber)
    {
        for (int i = 0; i < subscriberCount; i++)
        {
            if (balanceSubscribers[i] == subscriber)
            {
                balanceSubscribers[i] = balanceSubscribers[--subscriberCount];
                balanceSubscribers[subscriberCount] = null;
                break;
            }
        }
    }

    /// <summary>
    /// Notify all subscribers that the balance has changed.
    /// Called automatically after balance modifications.
    /// </summary>
    private void NotifyBalanceChanged()
    {
        for (int i = 0; i < subscriberCount; i++)
        {
            if (balanceSubscribers[i] != null)
            {
                balanceSubscribers[i].SendCustomEvent("OnBalanceChanged");
            }
        }
    }

    // Requests are only honoured by the owner, and only when the master sent them
    private bool IsAuthorityRequest()
    {
        return Networking.IsOwner(gameObject) && HoldemAuthority.IsAuthority(NetworkCalling.CallingPlayer);
    }

    //Helper to find the player balance component for a given VRCPlayerApi.
    public static PlayerBalanceComponent GetPlayerBalanceComponent(VRCPlayerApi Player)
    {
        if (Player == null || !Utilities.IsValid(Player))
        {
            return null;
        }

        foreach (var PlayerObject in Player.GetPlayerObjects())
        {
            if (Utilities.IsValid(PlayerObject))
            {
                PlayerBalanceComponent BalanceComponent = PlayerObject.GetComponentInChildren<PlayerBalanceComponent>();
                if (BalanceComponent)
                {
                    return BalanceComponent;
                }                
            }
        }

        return null;
    }

    public static int GetBalance(VRCPlayerApi Player)
    {
        PlayerBalanceComponent BalanceComponent = GetPlayerBalanceComponent(Player);
        if (BalanceComponent)
        {
            return BalanceComponent.GetBalance();
        }
        return 0;
    }

    public override void OnPlayerRestored(VRCPlayerApi Player)
    {
        base.OnPlayerRestored(Player);

        if (bIsReady)
        {
            return;
        }

        if (!Networking.IsOwner(gameObject) || !Player.isLocal)
        {
            return;
        }

        // Find UdonChips instance if not already set
        if (udonChips == null)
        {
            udonChips = GetComponent<UdonChips>();
        }

        // Load balance from UdonChips persistence
        if (udonChips != null)
        {
            CurrentSyncedBalance = (int)udonChips.money;
            Debug.Log($"[PlayerBalanceComponent] Loaded balance from UdonChips: {CurrentSyncedBalance}");
        }
        else
        {
            Debug.LogError("[PlayerBalanceComponent] UdonChips not found! Balance will be 0.");
            CurrentSyncedBalance = 0;
        }

        bIsReady = true;

        RequestSerialization();
        
        // Notify subscribers that balance is now ready
        NotifyBalanceChanged();
    }

    public int GetBalance()
    {
        if (!IsReady())
        {
            Debug.LogError("PlayerBalanceComponent::GetBalance() WAS CALLED BEFORE IT WAS READY.");
            return -1;
        }
        
        // Return the networked synced balance
        return CurrentSyncedBalance;
    }

    public void ModifyBalance(int Delta)
    {
        if (!IsReady())
        {
            Debug.LogError("PlayerBalanceComponent::ModifyBalance() WAS CALLED FROM BEFORE IT WAS READY.");
            return;
        }
        
        // Only the owner should modify the balance
        if (!Networking.IsOwner(gameObject))
        {
            Debug.Log($"[PlayerBalanceComponent] Not owner, sending network event to owner for delta: {Delta}");
            if (authority != null) authority._RecordCharge(this, Delta);
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestModifyBalance), Delta);
            return;
        }

        // Calculate new balance
        int NewBalance = Math.Max(CurrentSyncedBalance + Delta, 0);
        CurrentSyncedBalance = NewBalance;
        
        // Sync to all players
        RequestSerialization();
        
        // Save to UdonChips for persistence (local player's data)
        if (udonChips != null)
        {
            udonChips.money = CurrentSyncedBalance;
            if (udonChips.saveMode != UdonChipsSaveMode.Off)
            {
                udonChips.ManualSave();
            }
        }
        
        Debug.Log($"[PlayerBalanceComponent] Modified balance by {Delta}, new balance: {CurrentSyncedBalance}");
        NotifyBalanceChanged();
    }

    [NetworkCallable]
    public void RequestModifyBalance(int Delta)
    {
        if (!IsAuthorityRequest()) return;
        ModifyBalance(Delta);
    }

    public override void OnDeserialization()
    {
        // When we receive a synced update, update our local UdonChips
        // This ensures the local player's UdonChips reflects the networked value
        if (CurrentSyncedBalance >= 0 && udonChips != null && Networking.IsOwner(gameObject))
        {
            udonChips.money = CurrentSyncedBalance;
            // Don't call ManualSave here - we don't want to trigger persistence on every sync
        }
        
        bIsReady = CurrentSyncedBalance >= 0;
        
        // Notify subscribers that balance has been updated
        NotifyBalanceChanged();
    }

    private const string PersistenceFoldsKey             = SaveKeyPrefix + "HoldemFolds";
    private const string PersistenceWinsKey              = SaveKeyPrefix + "HoldemWins";
    private const string PersistenceLossesKey            = SaveKeyPrefix + "HoldemLosses";
    private const string PersistenceDonationsKey         = SaveKeyPrefix + "HoldemDonations";
    private const string PersistenceDonationsReceivedKey = SaveKeyPrefix + "HoldemDonationsReceived";
    private const string PersistenceProfitKey            = SaveKeyPrefix + "HoldemProfit";
    // V2 keys: the amount and the cards are separate values. The V1 keys (HoldemBiggestWin / HoldemBiggestWinHand)
    // hold untrustworthy values in prod and are intentionally never read or written any more.
    private const string PersistenceBiggestWinKey        = SaveKeyPrefix + "HoldemBigWinAmountV2";
    private const string PersistenceBiggestWinHandKey    = SaveKeyPrefix + "HoldemBigWinCardsV2";
    private const string HandKeyPrefix                   = SaveKeyPrefix + "HoldemHand";
    private const string PersistenceHatsGivenKey         = SaveKeyPrefix + "HatsGiven";
    private const string PersistenceHatsReceivedKey      = SaveKeyPrefix + "HatsReceived";
    private const string PersistenceTrackedHandsKey      = SaveKeyPrefix + "HoldemTrackedHands";
    private const string PersistenceVpipHandsKey         = SaveKeyPrefix + "HoldemVpipHands";
    private const string PersistencePfrHandsKey          = SaveKeyPrefix + "HoldemPfrHands";
    private const string PersistenceThreeBetOpportunitiesKey = SaveKeyPrefix + "HoldemThreeBetOpportunities";
    private const string PersistenceThreeBetsKey         = SaveKeyPrefix + "HoldemThreeBets";
    private const string PersistenceFoldToThreeBetOpportunitiesKey = SaveKeyPrefix + "HoldemFoldToThreeBetOpportunities";
    private const string PersistenceFoldsToThreeBetKey   = SaveKeyPrefix + "HoldemFoldsToThreeBet";
    private const string PersistenceCBetOpportunitiesKey = SaveKeyPrefix + "HoldemCBetOpportunities";
    private const string PersistenceCBetsKey             = SaveKeyPrefix + "HoldemCBets";
    private const string PersistenceFoldToCBetOpportunitiesKey = SaveKeyPrefix + "HoldemFoldToCBetOpportunities";
    private const string PersistenceFoldsToCBetKey       = SaveKeyPrefix + "HoldemFoldsToCBet";

    public const int
        HAND_STAT_TRACKED = 1 << 0,
        HAND_STAT_VPIP = 1 << 1,
        HAND_STAT_PFR = 1 << 2,
        HAND_STAT_THREE_BET_OPPORTUNITY = 1 << 3,
        HAND_STAT_THREE_BET = 1 << 4,
        HAND_STAT_FOLD_TO_THREE_BET_OPPORTUNITY = 1 << 5,
        HAND_STAT_FOLD_TO_THREE_BET = 1 << 6,
        HAND_STAT_CBET_OPPORTUNITY = 1 << 7,
        HAND_STAT_CBET = 1 << 8,
        HAND_STAT_FOLD_TO_CBET_OPPORTUNITY = 1 << 9,
        HAND_STAT_FOLD_TO_CBET = 1 << 10,
        HAND_STAT_ALL = (1 << 11) - 1;

    public const int
        STAT_FOLDS = 0,
        STAT_WINS = 1,
        STAT_LOSSES = 2,
        STAT_DONATIONS = 3,
        STAT_DONATIONS_RECEIVED = 4,
        STAT_HATS_GIVEN = 5,
        STAT_HATS_RECEIVED = 6;

    private string[] statKeys = new string[]
    {
        PersistenceFoldsKey, PersistenceWinsKey, PersistenceLossesKey, PersistenceDonationsKey,
        PersistenceDonationsReceivedKey, PersistenceHatsGivenKey, PersistenceHatsReceivedKey
    };

    private void AddToPersistentInt(string key, int value)
    {
        // PlayerData.SetInt writes the local player's data, so only the owner may write
        if (!Networking.IsOwner(gameObject)) return;
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        int current = 0;
        if (owner != null && PlayerData.HasKey(owner, key))
        {
            current = PlayerData.GetInt(owner, key);
        }
        PlayerData.SetInt(key, current + value);
        // Notify subscribers that stats have changed
        NotifyBalanceChanged();
    }

    private int GetPersistentInt(string key)
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        if (owner != null && PlayerData.HasKey(owner, key))
        {
            return PlayerData.GetInt(owner, key);
        }
        return 0;
    }

    private void RecordStat(int statId)
    {
        if (statId < 0 || statId >= statKeys.Length) return;
        if (Networking.IsOwner(gameObject))
        {
            AddToPersistentInt(statKeys[statId], 1);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordStat), statId);
        }
    }

    [NetworkCallable]
    public void RequestRecordStat(int statId)
    {
        if (!IsAuthorityRequest()) return;
        if (statId < 0 || statId >= statKeys.Length) return;
        AddToPersistentInt(statKeys[statId], 1);
    }

    public void _RecordFold() { RecordStat(STAT_FOLDS); }
    public void _RecordWin() { RecordStat(STAT_WINS); }
    public void _RecordLoss() { RecordStat(STAT_LOSSES); }
    public void _RecordDonation() { RecordStat(STAT_DONATIONS); }
    public void _RecordDonationReceived() { RecordStat(STAT_DONATIONS_RECEIVED); }
    public void _RecordHatGiven() { RecordStat(STAT_HATS_GIVEN); }
    public void _RecordHatReceived() { RecordStat(STAT_HATS_RECEIVED); }

    private bool IsValidHoldemHandStats(int statsMask)
    {
        if ((statsMask & HAND_STAT_TRACKED) == 0 || (statsMask & ~HAND_STAT_ALL) != 0) return false;
        if ((statsMask & HAND_STAT_PFR) != 0 && (statsMask & HAND_STAT_VPIP) == 0) return false;
        if ((statsMask & HAND_STAT_THREE_BET) != 0
            && (statsMask & (HAND_STAT_THREE_BET_OPPORTUNITY | HAND_STAT_PFR))
                != (HAND_STAT_THREE_BET_OPPORTUNITY | HAND_STAT_PFR)) return false;
        if ((statsMask & HAND_STAT_FOLD_TO_THREE_BET) != 0
            && (statsMask & HAND_STAT_FOLD_TO_THREE_BET_OPPORTUNITY) == 0) return false;
        if ((statsMask & HAND_STAT_CBET) != 0
            && (statsMask & (HAND_STAT_CBET_OPPORTUNITY | HAND_STAT_PFR))
                != (HAND_STAT_CBET_OPPORTUNITY | HAND_STAT_PFR)) return false;
        if ((statsMask & HAND_STAT_FOLD_TO_CBET) != 0
            && (statsMask & HAND_STAT_FOLD_TO_CBET_OPPORTUNITY) == 0) return false;
        return true;
    }

    private void AddHoldemHandStats(int statsMask)
    {
        if (!IsValidHoldemHandStats(statsMask)) return;

        if ((statsMask & HAND_STAT_TRACKED) != 0) AddToPersistentInt(PersistenceTrackedHandsKey, 1);
        if ((statsMask & HAND_STAT_VPIP) != 0) AddToPersistentInt(PersistenceVpipHandsKey, 1);
        if ((statsMask & HAND_STAT_PFR) != 0) AddToPersistentInt(PersistencePfrHandsKey, 1);
        if ((statsMask & HAND_STAT_THREE_BET_OPPORTUNITY) != 0) AddToPersistentInt(PersistenceThreeBetOpportunitiesKey, 1);
        if ((statsMask & HAND_STAT_THREE_BET) != 0) AddToPersistentInt(PersistenceThreeBetsKey, 1);
        if ((statsMask & HAND_STAT_FOLD_TO_THREE_BET_OPPORTUNITY) != 0) AddToPersistentInt(PersistenceFoldToThreeBetOpportunitiesKey, 1);
        if ((statsMask & HAND_STAT_FOLD_TO_THREE_BET) != 0) AddToPersistentInt(PersistenceFoldsToThreeBetKey, 1);
        if ((statsMask & HAND_STAT_CBET_OPPORTUNITY) != 0) AddToPersistentInt(PersistenceCBetOpportunitiesKey, 1);
        if ((statsMask & HAND_STAT_CBET) != 0) AddToPersistentInt(PersistenceCBetsKey, 1);
        if ((statsMask & HAND_STAT_FOLD_TO_CBET_OPPORTUNITY) != 0) AddToPersistentInt(PersistenceFoldToCBetOpportunitiesKey, 1);
        if ((statsMask & HAND_STAT_FOLD_TO_CBET) != 0) AddToPersistentInt(PersistenceFoldsToCBetKey, 1);
    }

    public void RecordHoldemHandStats(int statsMask)
    {
        if (!IsValidHoldemHandStats(statsMask)) return;
        if (Networking.IsOwner(gameObject))
        {
            AddHoldemHandStats(statsMask);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHoldemHandStats), statsMask);
        }
    }

    [NetworkCallable]
    public void RequestRecordHoldemHandStats(int statsMask)
    {
        if (IsAuthorityRequest()) AddHoldemHandStats(statsMask);
    }

    public void RecordProfit(int delta)
    {
#if !COMPILER_UDONSHARP && UNITY_EDITOR
        mockProfit += delta;
#endif
        if (Networking.IsOwner(gameObject))
        {
            AddToPersistentInt(PersistenceProfitKey, delta);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordProfit), delta);
        }
    }

    [NetworkCallable]
    public void RequestRecordProfit(int delta)
    {
        if (IsAuthorityRequest()) AddToPersistentInt(PersistenceProfitKey, delta);
    }

    public int GetFolds() { return GetPersistentInt(PersistenceFoldsKey); }
    public int GetWins() { return GetPersistentInt(PersistenceWinsKey); }
    public int GetLosses() { return GetPersistentInt(PersistenceLossesKey); }
    public int GetDonation() { return GetPersistentInt(PersistenceDonationsKey); }
    public int GetDonationsReceived() { return GetPersistentInt(PersistenceDonationsReceivedKey); }
    public int GetHatsGiven() { return GetPersistentInt(PersistenceHatsGivenKey); }
    public int GetHatsReceived() { return GetPersistentInt(PersistenceHatsReceivedKey); }
    public int GetTrackedHands() { return GetPersistentInt(PersistenceTrackedHandsKey); }
    public int GetVpipHands() { return GetPersistentInt(PersistenceVpipHandsKey); }
    public int GetPfrHands() { return GetPersistentInt(PersistencePfrHandsKey); }
    public int GetThreeBetOpportunities() { return GetPersistentInt(PersistenceThreeBetOpportunitiesKey); }
    public int GetThreeBets() { return GetPersistentInt(PersistenceThreeBetsKey); }
    public int GetFoldToThreeBetOpportunities() { return GetPersistentInt(PersistenceFoldToThreeBetOpportunitiesKey); }
    public int GetFoldsToThreeBet() { return GetPersistentInt(PersistenceFoldsToThreeBetKey); }
    public int GetCBetOpportunities() { return GetPersistentInt(PersistenceCBetOpportunitiesKey); }
    public int GetCBets() { return GetPersistentInt(PersistenceCBetsKey); }
    public int GetFoldToCBetOpportunities() { return GetPersistentInt(PersistenceFoldToCBetOpportunitiesKey); }
    public int GetFoldsToCBet() { return GetPersistentInt(PersistenceFoldsToCBetKey); }

    private float Percentage(int numerator, int denominator)
    {
        return denominator > 0 ? numerator * 100f / denominator : 0f;
    }

    public float GetVPIPPercent() { return Percentage(GetVpipHands(), GetTrackedHands()); }
    public float GetPFRPercent() { return Percentage(GetPfrHands(), GetTrackedHands()); }
    public float GetThreeBetPercent() { return Percentage(GetThreeBets(), GetThreeBetOpportunities()); }
    public float GetFoldToThreeBetPercent() { return Percentage(GetFoldsToThreeBet(), GetFoldToThreeBetOpportunities()); }
    public float GetCBetPercent() { return Percentage(GetCBets(), GetCBetOpportunities()); }
    public float GetFoldToCBetPercent() { return Percentage(GetFoldsToCBet(), GetFoldToCBetOpportunities()); }

    public int GetHandsPlayed()
    {
        return GetWins() + GetLosses() + GetFolds();
    }

    public int GetProfit()
    {
#if !COMPILER_UDONSHARP && UNITY_EDITOR
        {
            var testOwner = Networking.GetOwner(gameObject);
            if (testOwner == null || Networking.LocalPlayer == null)
            {
                return mockProfit;
            }
        }
#endif
        return GetPersistentInt(PersistenceProfitKey);
    }

    // Indexed by HoldemGame.GetHandClassInt
    private string[] handClassNames = new string[]
    {
        "HighCard", "Pair", "TwoPairs", "ThreeOfAKind", "Straight",
        "Flush", "FullHouse", "FourOfAKind", "StraightFlush", "RoyalFlush"
    };

    private void IncrementHandCount(int handClass)
    {
        if (handClass < 0 || handClass >= handClassNames.Length) return;
        AddToPersistentInt(HandKeyPrefix + handClassNames[handClass], 1);
    }

    public void RecordHandClass(int handClass)
    {
        if (Networking.IsOwner(gameObject))
        {
            IncrementHandCount(handClass);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandClass), handClass);
        }
    }

    [NetworkCallable]
    public void RequestRecordHandClass(int handClass)
    {
        if (IsAuthorityRequest()) IncrementHandCount(handClass);
    }

    // Showdown pot share and the five cards that won it (HoldemHandEvaluator.PackBestFive).
    // Only a strictly larger amount replaces the record, so a tie keeps the older hand.
    public void RecordBiggestWin(int amount, int packedHand)
    {
        Debug.Log($"[Metrics] RecordBiggestWin ENTRY: amount {amount}, cards packed {packedHand}, owner {Networking.IsOwner(gameObject)}");
        if (Networking.IsOwner(gameObject))
        {
            TryUpdateBiggestWin(amount, packedHand);
        }
        else
        {
            // One int per event with names no other method uses. A single two-int event delivered its first
            // argument corrupted in VRChat (sent 60, received 0 and 620756992) while the second arrived intact.
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestBigWinCards), packedHand);
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestBigWinAmount), amount);
        }
    }

    // The owner holds each half until the other arrives, in either order, then records both together.
    private int pendingBigWinAmount;
    private int pendingBigWinCards;
    private bool hasPendingBigWinAmount;
    private bool hasPendingBigWinCards;

    [NetworkCallable]
    public void RequestBigWinCards(int bigWinCards)
    {
        Debug.Log($"[Metrics] RequestBigWinCards RECEIVED: cards packed {bigWinCards}, authority {IsAuthorityRequest()}");
        if (!IsAuthorityRequest()) return;
        pendingBigWinCards = bigWinCards;
        hasPendingBigWinCards = true;
        CommitPendingBigWin();
    }

    [NetworkCallable]
    public void RequestBigWinAmount(int bigWinAmount)
    {
        Debug.Log($"[Metrics] RequestBigWinAmount RECEIVED: amount {bigWinAmount}, authority {IsAuthorityRequest()}");
        if (!IsAuthorityRequest()) return;
        pendingBigWinAmount = bigWinAmount;
        hasPendingBigWinAmount = true;
        CommitPendingBigWin();
    }

    private void CommitPendingBigWin()
    {
        if (!hasPendingBigWinAmount || !hasPendingBigWinCards) return;
        hasPendingBigWinAmount = false;
        hasPendingBigWinCards = false;
        TryUpdateBiggestWin(pendingBigWinAmount, pendingBigWinCards);
    }

    private void TryUpdateBiggestWin(int amount, int packedHand)
    {
        if (amount <= GetBiggestWin()) return;
        Debug.Log($"[Metrics] new biggest win {amount}, cards packed {packedHand}");
        // PlayerData.SetInt writes the local player's data, so only the owner may write
        PlayerData.SetInt(PersistenceBiggestWinKey, amount);
        PlayerData.SetInt(PersistenceBiggestWinHandKey, packedHand);
        NotifyBalanceChanged();
    }

    public int GetBiggestWin() { return GetPersistentInt(PersistenceBiggestWinKey); }
    public int GetBiggestWinHand() { return GetPersistentInt(PersistenceBiggestWinHandKey); }

    public int GetHandCount(string handName)
    {
        return GetPersistentInt(HandKeyPrefix + handName);
    }

    private void Update()
    {
        // Only owner should send periodic syncs
        if (!Networking.IsOwner(gameObject))
        {
            return;
        }

        // Periodically request serialization to ensure balance is synced reliably
        syncTimer += Time.deltaTime;
        if (syncTimer >= SYNC_INTERVAL)
        {
            syncTimer = 0f;

            if (bIsReady)
            {
                RequestSerialization();
            }
        }
    }
}
