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

namespace UdonChipsHat
{
    /// <summary>
    /// Global manager that handles hat state, rendering via pool, and economy.
    /// Uses a pool of HatInteract objects positioned on player heads.
    /// Master owns this object and syncs hat state for all players.
    /// </summary>
    [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
    public class HatManager : UdonSharpBehaviour
    {
        #region Persistence Keys
        
        // PlayerData keys (namespaced) - each player saves their own hat state locally
        private const string PersistenceHatTypeKey = "UdonChipsHat/Type";
        private const string PersistenceGiverKey = "UdonChipsHat/Giver";
        private const string PersistenceHasHatKey = "UdonChipsHat/HasHat";
        
        #endregion

        #region Hat Event Broadcasting
        
        [Header("Hat Event Subscribers")]
        [Tooltip("Components that inherit from HatEventSubscriber and will receive OnHatEvent calls")]
        private HatEventSubscriber[] hatEventSubscribers;

        /// <summary>
        /// Subscribes a HatEventSubscriber to receive hat events.
        /// Finds the first empty slot and assigns the subscriber.
        /// </summary>
        /// <param name="subscriber">The subscriber to register</param>
        public void Subscribe(HatEventSubscriber subscriber)
        {
            if (subscriber == null) return;

            // Initialize array if needed
            if (hatEventSubscribers == null)
            {
                hatEventSubscribers = new HatEventSubscriber[8];
            }

            // Check if already subscribed
            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                if (hatEventSubscribers[i] == subscriber)
                {
                    return; // Already subscribed
                }
            }

            // Find first empty slot
            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                if (hatEventSubscribers[i] == null)
                {
                    hatEventSubscribers[i] = subscriber;
                    Debug.Log($"[HatManager] Subscriber registered at index {i}");
                    return;
                }
            }

            Debug.LogWarning("[HatManager] Could not register subscriber - array is full");
        }

        #endregion

        #region Global Economy Settings (Shared by all hats)
        
        [Header("Global Economy Settings")]
        [Tooltip("Cost in UdonChips to place ANY hat on another player")]
        public int costToPlaceHat = 1000;

        [Tooltip("Amount the target player receives when ANY hat is placed on them")]
        public int rewardToTarget = 500;

        [Tooltip("Cost in UdonChips to remove a hat (paid by the remover)")]
        public int costToRemoveHat = 5000;
        
        #endregion

        #region Hat Pool

        [Header("Hat Pool")]
        [Tooltip("Pool of HatInteract objects (one per possible hat)")]
        public HatInteract[] hatInteractPool;

        [Tooltip("Maximum number of players to support")]
        public int maxPlayers = 80;

        #endregion

        #region Hat Visual Definitions

        [Header("Hat Prefabs")]
        [Tooltip("Prefab GameObjects containing MeshRenderer for each hat type")]
        public GameObject[] hatPrefabs;

        [Tooltip("Offset from head position for each hat type")]
        public Vector3[] hatOffsets;

        [Tooltip("Scale multiplier for each hat type")]
        public float[] hatScaleMultipliers;

        [Tooltip("Hat type ID for which the seatObject (e.g., halo) should be visible on other players")]
        public byte seatObjectHatTypeId = 3;

        [Tooltip("Base avatar eye height for default scaling")]
        public float baseAvatarHeight = 1.6f;

        #endregion

        #region Synced State (Indexed by Player ID)

        // Synced arrays - index is player ID (0-79)
        [UdonSynced]
        public byte[] PlayerHatTypes;

        [UdonSynced]
        public bool[] PlayerHasHats;

        [UdonSynced]
        public string[] PlayerGiverNames;

        #endregion

        #region Internal State

        // Pool tracking - which player ID is assigned to each pool slot
        private int[] poolPlayerAssignments;  // Length = hatInteractPool.Length
        private int[] playerPoolSlot;         // Length = maxPlayers, value = pool slot or -1
        
        // Cached slot-used array for UpdateHatPositions (avoids per-frame allocation)
        private bool[] _slotUsed;

        // Player tracking
        private VRCPlayerApi[] allPlayers;
        private int playerCount;
        private bool _playersDirty = true;

        // Local pending tracking to prevent double-hat
        private int[] pendingHatFrame;  // Frame count when hat was requested
        private const int PENDING_FRAMES = 120; // ~2 seconds at 60fps

        // Initial load tracking
        private bool initialLoadTriggered = false;

        private bool persistenceRestoreComplete = false;

        // Set while waiting for the master to confirm a requested hat restore
        private bool awaitingRestoreApply = false;

        private bool lastSavedHasHat = false;
        private byte lastSavedHatType = 0;
        private string lastSavedGiverName = "";


        // Track previous hat state to detect removals
        private bool[] previousPlayerHasHats;
        private byte[] previousPlayerHatTypes;

        #endregion

        void Start()
        {
            // Initialize synced arrays. Only allocate when missing.
            if (PlayerHatTypes == null || PlayerHatTypes.Length != maxPlayers)
            {
                PlayerHatTypes = new byte[maxPlayers];
            }
            if (PlayerHasHats == null || PlayerHasHats.Length != maxPlayers)
            {
                PlayerHasHats = new bool[maxPlayers];
            }
            if (PlayerGiverNames == null || PlayerGiverNames.Length != maxPlayers)
            {
                PlayerGiverNames = new string[maxPlayers];
            }

            // Initialize tracking arrays
            poolPlayerAssignments = new int[hatInteractPool != null ? hatInteractPool.Length : 0];
            playerPoolSlot = new int[maxPlayers];
            pendingHatFrame = new int[maxPlayers];
            allPlayers = new VRCPlayerApi[maxPlayers];

            // Initialize pool assignments to -1 (unassigned)
            for (int i = 0; i < poolPlayerAssignments.Length; i++)
            {
                poolPlayerAssignments[i] = -1;
            }
            for (int i = 0; i < playerPoolSlot.Length; i++)
            {
                playerPoolSlot[i] = -1;
                pendingHatFrame[i] = 0;
            }

            // Initialize pool objects
            if (hatInteractPool != null)
            {
                for (int i = 0; i < hatInteractPool.Length; i++)
                {
                    if (hatInteractPool[i] != null)
                    {
                        hatInteractPool[i].Initialize(this, i);
                        hatInteractPool[i].gameObject.SetActive(false);
                    }
                }
            }

            // Initialize previous state tracking arrays
            previousPlayerHasHats = new bool[maxPlayers];
            previousPlayerHatTypes = new byte[maxPlayers];
            for (int i = 0; i < maxPlayers; i++)
            {
                previousPlayerHasHats[i] = false;
                previousPlayerHatTypes[i] = 0;
            }
        }

        public override void OnDeserialization()
        {
            TryCompleteRestoreFromSyncedState();
            ApplyLocalHatEffects();
            SaveLocalHatStateToPersistence();
        }

        public void BeginPersistenceRestore()
        {
            awaitingRestoreApply = true;
        }

        private void TryCompleteRestoreFromSyncedState()
        {
            if (!awaitingRestoreApply) return;

            VRCPlayerApi local = Networking.LocalPlayer;
            if (local == null || !local.IsValid()) return;

            int localPlayerId = local.playerId;
            if (localPlayerId < 0 || localPlayerId >= maxPlayers) return;
            if (PlayerHasHats == null || localPlayerId >= PlayerHasHats.Length) return;

            if (PlayerHasHats[localPlayerId])
            {
                MarkPersistenceRestoreComplete();
            }
        }

        public void MarkPersistenceRestoreComplete()
        {
            persistenceRestoreComplete = true;
            awaitingRestoreApply = false;

            ApplyLocalHatEffects();
            SaveLocalHatStateToPersistence();
        }

        public bool IsPersistenceRestoreComplete()
        {
            return persistenceRestoreComplete;
        }

        /// <summary>
        /// Applies hat effects for the local player based on synced state.
        /// Called from OnDeserialization for non-owners and directly by owner
        /// after modifying state since OnDeserialization doesn't run for the owner.
        /// </summary>
        private void ApplyLocalHatEffects()
        {
            // Get local player
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer == null || !localPlayer.IsValid()) return;

            int localPlayerId = localPlayer.playerId;
            if (localPlayerId < 0 || localPlayerId >= maxPlayers) return;

            // Only consumed if hat is actually present
            if (!initialLoadTriggered)
            {
                // Check if local player has a hat
                if (PlayerHasHats[localPlayerId])
                {
                    byte hatType = PlayerHatTypes[localPlayerId];
                    string giverName = PlayerGiverNames[localPlayerId];
                    
                    initialLoadTriggered = true;
                    BroadcastHatInitialLoad(hatType, giverName);
                }
            }

            // Check for hat removal (previous state had hat, current state doesn't)
            if (previousPlayerHasHats[localPlayerId] && !PlayerHasHats[localPlayerId])
            {
                byte previousHatType = previousPlayerHatTypes[localPlayerId];
                BroadcastHatRemoved(previousHatType, "");
            }

            // Update previous state tracking for local player
            previousPlayerHasHats[localPlayerId] = PlayerHasHats[localPlayerId];
            previousPlayerHatTypes[localPlayerId] = PlayerHatTypes[localPlayerId];
        }

        /// <summary>
        /// Saves the local player's hat state to their own PlayerData persistence.
        /// Called from OnDeserialization when synced data is received.
        /// Each player can only save their own data - the master cannot save for others.
        /// </summary>
        private void SaveLocalHatStateToPersistence()
        {
            // Never write before the restore has been reconciled
            if (!persistenceRestoreComplete) return;
            WriteLocalHatStateToPersistence();
        }

        private void WriteLocalHatStateToPersistence()
        {
            // Get local player - we can only save our own data
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer == null || !localPlayer.IsValid()) return;

            int localPlayerId = localPlayer.playerId;
            if (localPlayerId < 0 || localPlayerId >= maxPlayers) return;

            // Get current hat state from synced arrays
            bool currentHasHat = PlayerHasHats[localPlayerId];
            byte currentHatType = PlayerHatTypes[localPlayerId];
            string currentGiverName = PlayerGiverNames[localPlayerId];
            if (currentGiverName == null) currentGiverName = "";

            if (currentHasHat == lastSavedHasHat
                && currentHatType == lastSavedHatType
                && currentGiverName == lastSavedGiverName)
            {
                return;
            }

            // Save to our own persistence (we can only save local player data)
            PlayerData.SetInt(PersistenceHatTypeKey, currentHatType);
            PlayerData.SetString(PersistenceGiverKey, currentGiverName);
            PlayerData.SetInt(PersistenceHasHatKey, currentHasHat ? 1 : 0);

            lastSavedHasHat = currentHasHat;
            lastSavedHatType = currentHatType;
            lastSavedGiverName = currentGiverName;

            Debug.Log($"[HatManager] Saved hat state to persistence: Type={currentHatType}, Giver={currentGiverName}, HasHat={currentHasHat}");
        }

        void PostLateUpdate()
        {
            UpdateHatPositions();
        }

        /// <summary>
        /// Updates positions of all pooled hat objects to follow player heads.
        /// </summary>
        private void UpdateHatPositions()
        {
            if (hatInteractPool == null || hatInteractPool.Length == 0) return;

            // Get all players (cached, only refreshes when players join/leave)
            RefreshPlayers();

            // Track which pool slots are used this frame (reuse cached array)
            int poolLen = hatInteractPool.Length;
            if (_slotUsed == null || _slotUsed.Length < poolLen)
                _slotUsed = new bool[poolLen];
            else
                for (int i = 0; i < poolLen; i++) _slotUsed[i] = false;
            bool[] slotUsed = _slotUsed;

            // Assign/update pool slots for players with hats
            for (int i = 0; i < playerCount; i++)
            {
                VRCPlayerApi player = allPlayers[i];
                if (player == null || !player.IsValid()) continue;

                int playerId = player.playerId;
                if (playerId < 0 || playerId >= maxPlayers) continue;

                // Check if player has a hat
                if (!PlayerHasHats[playerId]) continue;

                // Get or assign pool slot
                int slot = playerPoolSlot[playerId];
                if (slot < 0)
                {
                    slot = FindFreePoolSlot();
                    if (slot >= 0)
                    {
                        playerPoolSlot[playerId] = slot;
                        poolPlayerAssignments[slot] = playerId;
                    }
                }

                if (slot >= 0)
                {
                    slotUsed[slot] = true;
                    PositionHatAtHead(slot, player, PlayerHatTypes[playerId]);
                }
            }

            // Disable unused pool slots
            for (int i = 0; i < poolLen; i++)
            {
                if (!slotUsed[i] && hatInteractPool[i] != null && hatInteractPool[i].gameObject.activeSelf)
                {
                    hatInteractPool[i].gameObject.SetActive(false);
                    if (poolPlayerAssignments[i] >= 0)
                    {
                        playerPoolSlot[poolPlayerAssignments[i]] = -1;
                        poolPlayerAssignments[i] = -1;
                    }
                }
            }
        }

        /// <summary>
        /// Refreshes the cached player list if dirty (players joined/left).
        /// </summary>
        private void RefreshPlayers()
        {
            if (!_playersDirty) return;
            playerCount = VRCPlayerApi.GetPlayerCount();
            VRCPlayerApi.GetPlayers(allPlayers);
            _playersDirty = false;
        }

        /// <summary>
        /// Finds a free slot in the hat pool.
        /// </summary>
        private int FindFreePoolSlot()
        {
            for (int i = 0; i < poolPlayerAssignments.Length; i++)
            {
                if (poolPlayerAssignments[i] < 0)
                {
                    return i;
                }
            }
            return -1; // No free slots
        }

        /// <summary>
        /// Positions a pooled hat at the player's head.
        /// </summary>
        private void PositionHatAtHead(int poolSlot, VRCPlayerApi player, byte hatType)
        {
            if (poolSlot < 0 || poolSlot >= hatInteractPool.Length) return;
            if (hatInteractPool[poolSlot] == null) return;

            // Get head tracking data
            VRCPlayerApi.TrackingData headData = player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head);
            Vector3 headPos = headData.position;
            Quaternion headRot = headData.rotation;

            // Calculate scale based on avatar height
            float avatarScale = player.GetAvatarEyeHeightAsMeters() / baseAvatarHeight;
            float hatScale = avatarScale;

            // Apply hat-specific multiplier if available
            if (hatScaleMultipliers != null && hatType < hatScaleMultipliers.Length && hatScaleMultipliers[hatType] > 0)
            {
                hatScale *= hatScaleMultipliers[hatType];
            }

            // Apply hat-specific offset if available
            Vector3 offset = Vector3.zero;
            if (hatOffsets != null && hatType < hatOffsets.Length)
            {
                offset = hatOffsets[hatType];
            }

            // Position the root at head position (no offset here)
            Transform hatTransform = hatInteractPool[poolSlot].transform;
            hatTransform.position = headPos;
            hatTransform.rotation = headRot;
            // Note: Scale is applied in SetHatVisuals to avoid double-scaling
            hatTransform.localScale = Vector3.one;

            // Update mesh/material based on hat type, passing the offset and hat scale
            hatInteractPool[poolSlot].SetHatVisuals(hatType, offset, hatScale);

            // Enable seat object (e.g. halo) only for matching hat type and only on other players
            bool showSeatObject = (hatType == seatObjectHatTypeId) && !player.isLocal;
            hatInteractPool[poolSlot].SetSeatObjectActive(showSeatObject);

            hatInteractPool[poolSlot].assignedPlayerId = player.playerId;

            if (!hatInteractPool[poolSlot].gameObject.activeSelf)
            {
                hatInteractPool[poolSlot].gameObject.SetActive(true);
            }
        }

        public override void OnPlayerJoined(VRCPlayerApi player)
        {
            _playersDirty = true;
        }

        public override void OnPlayerLeft(VRCPlayerApi player)
        {
            _playersDirty = true;
            int playerId = player.playerId;
            if (playerId < 0 || playerId >= maxPlayers) return;

            // Free up pool slot
            int slot = playerPoolSlot[playerId];
            if (slot >= 0 && slot < hatInteractPool.Length)
            {
                if (hatInteractPool[slot] != null)
                {
                    hatInteractPool[slot].gameObject.SetActive(false);
                    hatInteractPool[slot].assignedPlayerId = -1;
                }
                poolPlayerAssignments[slot] = -1;
            }
            playerPoolSlot[playerId] = -1;

            // Clear pending flag
            pendingHatFrame[playerId] = 0;

            // Master clears hat state for left player
            if (Networking.IsOwner(gameObject))
            {
                PlayerHasHats[playerId] = false;
                PlayerHatTypes[playerId] = 0;
                PlayerGiverNames[playerId] = "";
                RequestSerialization();
            }
        }

        #region Public API - Called by HatItem/HatInteract

        /// <summary>
        /// Called by any player to request a hat be applied to a target.
        /// Only master processes this request.
        /// </summary>
        public void RequestApplyHat(int targetPlayerId, byte hatType, string giverName)
        {
            if (!Networking.IsOwner(gameObject))
            {
                // Forward to master
                SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(MasterApplyHat), targetPlayerId, hatType, giverName);
                return;
            }

            MasterApplyHat(targetPlayerId, hatType, giverName);
        }

        [NetworkCallable]
        public void MasterApplyHat(int targetPlayerId, byte hatType, string giverName)
        {
            if (!Networking.IsOwner(gameObject)) return;
            if (targetPlayerId < 0 || targetPlayerId >= maxPlayers) return;

            // Double-check target doesn't already have a hat
            if (PlayerHasHats[targetPlayerId])
            {
                Debug.Log($"[HatManager] Master rejected hat application - player {targetPlayerId} already has hat");
                return;
            }

            // Apply hat
            PlayerHatTypes[targetPlayerId] = hatType;
            PlayerGiverNames[targetPlayerId] = giverName;
            PlayerHasHats[targetPlayerId] = true;

            RequestSerialization();
            Debug.Log($"[HatManager] Applied hat type {hatType} to player {targetPlayerId} from {giverName}");

            // Apply effects for owner since OnDeserialization doesn't run for them
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer != null && localPlayer.IsValid() && localPlayer.playerId == targetPlayerId)
            {
                // local so is authoratative
                MarkPersistenceRestoreComplete();
            }
        }

        /// <summary>
        /// Called by any player to request a hat be removed from a target.
        /// Only master processes this request.
        /// </summary>
        public void RequestRemoveHat(int targetPlayerId)
        {
            if (!Networking.IsOwner(gameObject))
            {
                // Forward to master
                SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(MasterRemoveHat), targetPlayerId);
                return;
            }

            MasterRemoveHat(targetPlayerId);
        }

        [NetworkCallable]
        public void MasterRemoveHat(int targetPlayerId)
        {
            if (!Networking.IsOwner(gameObject)) return;
            if (targetPlayerId < 0 || targetPlayerId >= maxPlayers) return;

            if (!PlayerHasHats[targetPlayerId])
            {
                Debug.Log($"[HatManager] Master rejected hat removal - player {targetPlayerId} has no hat");
                return;
            }

            // Remove hat
            PlayerHasHats[targetPlayerId] = false;
            PlayerHatTypes[targetPlayerId] = 0;
            PlayerGiverNames[targetPlayerId] = "";

            RequestSerialization();
            Debug.Log($"[HatManager] Removed hat from player {targetPlayerId}");

            // Apply effects for owner since OnDeserialization doesn't run for them
            VRCPlayerApi localPlayer = Networking.LocalPlayer;
            if (localPlayer != null && localPlayer.IsValid() && localPlayer.playerId == targetPlayerId)
            {
                // local so is authoratative
                MarkPersistenceRestoreComplete();
            }
        }

        /// <summary>
        /// Force refresh of all hat positions (called after hat state changes)
        /// </summary>
        public void RefreshHats()
        {
            // The next PostLateUpdate will handle it
        }

        /// <summary>
        /// Get the cost to place any hat
        /// </summary>
        public int GetCostToPlace()
        {
            return costToPlaceHat;
        }

        /// <summary>
        /// Get the reward amount given to the target when any hat is placed
        /// </summary>
        public int GetRewardToTarget()
        {
            return rewardToTarget;
        }

        /// <summary>
        /// Get the cost to remove any hat
        /// </summary>
        public int GetCostToRemove()
        {
            return costToRemoveHat;
        }

        /// <summary>
        /// Check if a player has a hat
        /// </summary>
        public bool PlayerHasHat(int playerId)
        {
            if (playerId < 0 || playerId >= maxPlayers) return false;
            return PlayerHasHats[playerId];
        }

        /// <summary>
        /// Get the hat type for a player
        /// </summary>
        public byte GetPlayerHatType(int playerId)
        {
            if (playerId < 0 || playerId >= maxPlayers) return 0;
            return PlayerHatTypes[playerId];
        }

        #endregion

        #region Hat Event Broadcasting

        /// <summary>
        /// Broadcast an event to all HatBell instances.
        /// Uses SendCustomNetworkEvent with parameters to notify all clients.
        /// </summary>
        /// <param name="hatTypeId">Hat type to target (0-254), or 255 for any hat type</param>
        /// <param name="triggerPlayerName">Display name of player who triggered the event</param>
        public void BroadcastHatEvent(byte hatTypeId, string triggerPlayerName)
        {
            // Send network event with parameters to all clients
            // Each HatBell will receive this and check against its local HatPlayerData
            SendCustomNetworkEvent(NetworkEventTarget.All, nameof(OnHatEvent), hatTypeId, triggerPlayerName);

            Debug.Log($"[HatManager] Broadcasting event for hat type {hatTypeId} from {triggerPlayerName}");
        }

        /// <summary>
        /// Broadcasts the initial hat load event to all subscribers.
        /// Called once when the local player's persisted hat state is first received.
        /// This is a local-only call since data is already synced via persistence.
        /// </summary>
        /// <param name="hatTypeId">Hat type of the local player</param>
        /// <param name="triggerPlayerName">Display name of the player who gave the hat</param>
        public void BroadcastHatInitialLoad(byte hatTypeId, string triggerPlayerName)
        {
            Debug.Log($"[HatManager] Broadcasting initial load event for hat type {hatTypeId} from {triggerPlayerName}");

            if (hatEventSubscribers == null) return;

            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                HatEventSubscriber subscriber = hatEventSubscribers[i];
                if (subscriber == null) continue;

                subscriber.OnHatInitialLoad(hatTypeId, triggerPlayerName);
            }
        }

        /// <summary>
        /// Called on all clients via SendCustomNetworkEvent.
        /// Dispatches to all registered IHatEventSubscriber instances.
        /// </summary>
        [NetworkCallable]
        public void OnHatEvent(byte hatTypeId, string triggerPlayerName)
        {
            // This method is called on all clients via network event
            // HatBell instances subscribe to this and handle the logic locally
            Debug.Log($"[HatManager] Received event for hat type {hatTypeId} from {triggerPlayerName}");

            if (hatEventSubscribers == null) return;

            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                HatEventSubscriber subscriber = hatEventSubscribers[i];
                if (subscriber == null) continue;

                subscriber.OnHatEvent(hatTypeId, triggerPlayerName);
            }
        }

        /// <summary>
        /// Broadcasts the hat removed event to all subscribers.
        /// Called locally when a hat is removed from the local player.
        /// </summary>
        /// <param name="hatTypeId">Hat type that was removed</param>
        /// <param name="triggerPlayerName">Display name of the player who triggered the removal</param>
        public void BroadcastHatRemoved(byte hatTypeId, string triggerPlayerName)
        {
            Debug.Log($"[HatManager] Broadcasting hat removed event for hat type {hatTypeId}");

            if (hatEventSubscribers == null) return;

            for (int i = 0; i < hatEventSubscribers.Length; i++)
            {
                HatEventSubscriber subscriber = hatEventSubscribers[i];
                if (subscriber == null) continue;

                subscriber.OnHatRemoved(hatTypeId, triggerPlayerName);
            }
        }

        #endregion
    }
}
