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
{
    private const string PersistenceDunceCapKey = "HoldemDunceCap";

#if !COMPILER_UDONSHARP && UNITY_EDITOR
    private int mockProfit = 0;
#endif

    // Reference to UdonChips for persistence
    public UdonChips udonChips;

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

    [UdonSynced]
    public bool HasDunceCapSynced = false;

    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 IsBalanceReady() { return IsReady(); }
    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");
            }
        }
    }

    /// <summary>
    /// Called by UdonChips when money changes.
    /// Syncs UdonChips value to networked balance and notifies subscribers.
    /// Safe to call - subscribers are read-only (PanelBalance, WelfareComponent).
    /// </summary>
    public void OnMoneyChanged()
    {
        // Only owner should sync from UdonChips
        if (!Networking.IsOwner(gameObject)) return;
        if (udonChips == null) return;
        
        int newBalance = (int)udonChips.money;
        
        // Only update if value actually changed
        if (CurrentSyncedBalance != newBalance)
        {
            CurrentSyncedBalance = newBalance;
            RequestSerialization();
            
            // Notify subscribers (read-only: PanelBalance, WelfareComponent)
            // No loop risk - they don't call ModifyBalance()
            NotifyBalanceChanged();
            
            Debug.Log($"[PlayerBalanceComponent] Synced from UdonChips: {CurrentSyncedBalance}");
        }
    }

    //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 static void ModifyBalance(VRCPlayerApi Player, int Delta)
    {
        PlayerBalanceComponent BalanceComponent = GetPlayerBalanceComponent(Player);
        if (BalanceComponent)
        {
            BalanceComponent.ModifyBalance(Delta);
        }
    }
    
    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;

        // Load DunceCap state from persistence
        if (PlayerData.HasKey(Player, PersistenceDunceCapKey))
        {
            HasDunceCapSynced = PlayerData.GetInt(Player, PersistenceDunceCapKey) == 1;
        }
        else
        {
            PlayerData.SetInt(PersistenceDunceCapKey, 0);
            HasDunceCapSynced = false;
        }
        
        RequestSerialization();
        
        // Notify subscribers that balance is now ready
        NotifyBalanceChanged();
    }

    public int GetBalance()
    {
        if (!IsBalanceReady())
        {
            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 (!IsBalanceReady())
        {
            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}");
            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)
    {
        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();
    }

    public void ApplyDunceCap()
    {
        if (Networking.IsOwner(gameObject))
        {
            PlayerData.SetInt(PersistenceDunceCapKey, 1);
            HasDunceCapSynced = true;
            RequestSerialization();
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestApplyDunceCap));
        }
    }

    [NetworkCallable]
    public void RequestApplyDunceCap()
    {
        ApplyDunceCap();
    }

    public void RemoveDunceCap()
    {
        if (Networking.IsOwner(gameObject))
        {
            PlayerData.SetInt(PersistenceDunceCapKey, 0);
            HasDunceCapSynced = false;
            RequestSerialization();
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRemoveDunceCap));
        }
    }

    [NetworkCallable]
    public void RequestRemoveDunceCap()
    {
        RemoveDunceCap();
    }

    private const string PersistenceFoldsKey     = "HoldemFolds";
    private const string PersistenceWinsKey      = "HoldemWins";
    private const string PersistenceLossesKey    = "HoldemLosses";
    private const string PersistenceDonationsKey = "HoldemDonations";
    private const string PersistenceProfitKey    = "HoldemProfit";

    private void IncrementPersistentInt(string key)
    {
        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 + 1);
        // Notify subscribers that stats have changed
        NotifyBalanceChanged();
    }

    private void AddToPersistentInt(string key, int value)
    {
        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();
    }

    public void RecordFold()
    {
        if (Networking.IsOwner(gameObject))
        {
            IncrementPersistentInt(PersistenceFoldsKey);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordFold));
        }
    }

    [NetworkCallable]
    public void RequestRecordFold()
    {
        IncrementPersistentInt(PersistenceFoldsKey);
    }

    public void RecordWin()
    {
        if (Networking.IsOwner(gameObject))
        {
            IncrementPersistentInt(PersistenceWinsKey);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordWin));
        }
    }

    [NetworkCallable]
    public void RequestRecordWin()
    {
        IncrementPersistentInt(PersistenceWinsKey);
    }

    public void RecordLoss()
    {
        if (Networking.IsOwner(gameObject))
        {
            IncrementPersistentInt(PersistenceLossesKey);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordLoss));
        }
    }

    [NetworkCallable]
    public void RequestRecordLoss()
    {
        IncrementPersistentInt(PersistenceLossesKey);
    }

    public void RecordDonation()
    {
        if (Networking.IsOwner(gameObject))
        {
            IncrementPersistentInt(PersistenceDonationsKey);
        }
        else
        {
            SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordDonation));
        }
    }

    [NetworkCallable]
    public void RequestRecordDonation()
    {
        IncrementPersistentInt(PersistenceDonationsKey);
    }

    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)
    {
        AddToPersistentInt(PersistenceProfitKey, delta);
    }

    public int GetFolds()
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        if (owner != null && PlayerData.HasKey(owner, PersistenceFoldsKey))
        {
            return PlayerData.GetInt(owner, PersistenceFoldsKey);
        }
        return 0;
    }

    public int GetWins()
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        if (owner != null && PlayerData.HasKey(owner, PersistenceWinsKey))
        {
            return PlayerData.GetInt(owner, PersistenceWinsKey);
        }
        return 0;
    }

    public int GetLosses()
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        if (owner != null && PlayerData.HasKey(owner, PersistenceLossesKey))
        {
            return PlayerData.GetInt(owner, PersistenceLossesKey);
        }
        return 0;
    }

    public int GetDonation()
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        if (owner != null && PlayerData.HasKey(owner, PersistenceDonationsKey))
        {
            return PlayerData.GetInt(owner, PersistenceDonationsKey);
        }
        return 0;
    }

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

    private void IncrementHandCount(string handName)
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        string key = "HoldemHand" + handName;
        int current = 0;
        if (owner != null && PlayerData.HasKey(owner, key))
        {
            current = PlayerData.GetInt(owner, key);
        }
        PlayerData.SetInt(key, current + 1);
        // Notify subscribers that stats have changed
        NotifyBalanceChanged();
    }

    public void RecordHandHighCard() { if (Networking.IsOwner(gameObject)) IncrementHandCount("HighCard"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandHighCard)); }
    [NetworkCallable] public void RequestRecordHandHighCard() { IncrementHandCount("HighCard"); }
    public void RecordHandPair() { if (Networking.IsOwner(gameObject)) IncrementHandCount("Pair"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandPair)); }
    [NetworkCallable] public void RequestRecordHandPair() { IncrementHandCount("Pair"); }
    public void RecordHandTwoPairs() { if (Networking.IsOwner(gameObject)) IncrementHandCount("TwoPairs"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandTwoPairs)); }
    [NetworkCallable] public void RequestRecordHandTwoPairs() { IncrementHandCount("TwoPairs"); }
    public void RecordHandThreeOfAKind() { if (Networking.IsOwner(gameObject)) IncrementHandCount("ThreeOfAKind"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandThreeOfAKind)); }
    [NetworkCallable] public void RequestRecordHandThreeOfAKind() { IncrementHandCount("ThreeOfAKind"); }
    public void RecordHandStraight() { if (Networking.IsOwner(gameObject)) IncrementHandCount("Straight"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandStraight)); }
    [NetworkCallable] public void RequestRecordHandStraight() { IncrementHandCount("Straight"); }
    public void RecordHandFlush() { if (Networking.IsOwner(gameObject)) IncrementHandCount("Flush"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandFlush)); }
    [NetworkCallable] public void RequestRecordHandFlush() { IncrementHandCount("Flush"); }
    public void RecordHandFullHouse() { if (Networking.IsOwner(gameObject)) IncrementHandCount("FullHouse"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandFullHouse)); }
    [NetworkCallable] public void RequestRecordHandFullHouse() { IncrementHandCount("FullHouse"); }
    public void RecordHandFourOfAKind() { if (Networking.IsOwner(gameObject)) IncrementHandCount("FourOfAKind"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandFourOfAKind)); }
    [NetworkCallable] public void RequestRecordHandFourOfAKind() { IncrementHandCount("FourOfAKind"); }
    public void RecordHandStraightFlush() { if (Networking.IsOwner(gameObject)) IncrementHandCount("StraightFlush"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandStraightFlush)); }
    [NetworkCallable] public void RequestRecordHandStraightFlush() { IncrementHandCount("StraightFlush"); }
    public void RecordHandRoyalFlush() { if (Networking.IsOwner(gameObject)) IncrementHandCount("RoyalFlush"); else SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestRecordHandRoyalFlush)); }
    [NetworkCallable] public void RequestRecordHandRoyalFlush() { IncrementHandCount("RoyalFlush"); }

    public void RecordHandClass(int handClass)
    {
        switch (handClass)
        {
            case 0: RecordHandHighCard(); break;
            case 1: RecordHandPair(); break;
            case 2: RecordHandTwoPairs(); break;
            case 3: RecordHandThreeOfAKind(); break;
            case 4: RecordHandStraight(); break;
            case 5: RecordHandFlush(); break;
            case 6: RecordHandFullHouse(); break;
            case 7: RecordHandFourOfAKind(); break;
            case 8: RecordHandStraightFlush(); break;
            case 9: RecordHandRoyalFlush(); break;
        }
    }

    public int GetHandCount(string handName)
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) owner = Networking.LocalPlayer;
        string key = "HoldemHand" + handName;
        if (owner != null && PlayerData.HasKey(owner, key))
        {
            return PlayerData.GetInt(owner, key);
        }
        return 0;
    }

    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();
            }
        }
    }
}
