using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using VRC.SDK3.UdonNetworkCalling;
using VRC.Udon.Common.Interfaces;
using VRC.SDK3.Components;

namespace UdonChipsHat
{
    /// <summary>
    /// A bell that can be rung by players to trigger hat events.
    /// When rung via acceleration while held, broadcasts an event to all HatBell instances.
    /// Each HatBell checks against HatManager's local state.
    /// </summary>
    [UdonBehaviourSyncMode(BehaviourSyncMode.Continuous)]
    public class HatBell : HatEventSubscriber
    {
        [Header("Hat Manager")]
        [Tooltip("Reference to HatManager")]
        public HatManager hatManager;

        [Header("Bell Settings")]
        [Tooltip("Hat type ID to target (0-254), or 255 for any hat type")]
        public byte targetHatTypeId = 1;

        [Tooltip("Cooldown in seconds between rings (0 = no cooldown)")]
        public float cooldown = 1.0f;

        [Tooltip("Only trigger if the ringer is the one who gave us the hat")]
        public bool onlyTriggerForGiver = true;

        [Header("Bell End Transform")]
        [Tooltip("Transform to track for acceleration (the 'end' of the bell that moves). If null, uses this.transform")]
        public Transform bellEndTransform;

        [Header("Acceleration Detection")]
        [Tooltip("Acceleration threshold to trigger bell ring")]
        public float accelerationThreshold = 15.0f;

        [Tooltip("Duration in seconds to apply damping curve after pickup")]
        public float dampingDuration = 0.5f;

        [Tooltip("Animation curve for damping acceleration (0-1 on both axes). EaseOut style recommended.")]
        public AnimationCurve dampingCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);

        [Header("Audio")]
        [Tooltip("Sound to play when the bell is rung locally (normal spatial audio)")]
        public AudioSource localBellSound;

        [Tooltip("Sound to play for OnHatEvent with large near radius (hearable from anywhere)")]
        public AudioSource eventBellSound;

        [Header("Return to Anchor")]
        [Tooltip("Transform to return to after not being held (null = disable)")]
        public Transform returnAnchor;

        [Tooltip("Seconds to wait after dropping before returning (-1 = disable)")]
        public float returnDelay = 5f;

        [Header("Particles")]
        [SerializeField] private ParticleSystem soundParticles;

        // State
        private VRCPlayerApi localPlayer;
        private float lastRingTime = -999f;

        // Pickup and acceleration tracking
        public VRC_Pickup pickup;
        public VRCObjectSync objectSync;
        public Transform bellTransform;
        private bool isHeld = false;
        private float pickupTime = 0f;
        private float lastDropTime = -1f;
        private Vector3 lastPosition;
        private Vector3 lastVelocity;

        void Start()
        {
            localPlayer = Networking.LocalPlayer;

            // Default bellEndTransform to this transform if not set
            if (bellEndTransform == null)
            {
                bellEndTransform = transform;
            }

            if (hatManager == null)
            {
                Debug.LogError("[HatBell] HatManager not found in scene!");
            }
            else
            {
                // Auto-subscribe to HatManager's event subscribers
                hatManager.Subscribe(this);
            }
        }

        public override void OnPickup()
        {
            isHeld = true;
            pickupTime = Time.time;
            lastDropTime = -1f;

            // Initialize position and velocity tracking
            if (bellEndTransform != null)
            {
                lastPosition = bellEndTransform.position;
                lastVelocity = Vector3.zero;
            }
        }

        public override void OnDrop()
        {
            isHeld = false;
            lastVelocity = Vector3.zero;
            lastDropTime = Time.time;
        }

        void Update()
        {
            // Handle return to anchor when not held
            if (!isHeld && returnAnchor != null && returnDelay >= 0f && lastDropTime >= 0f)
            {
                if (Time.time - lastDropTime >= returnDelay)
                {
                    if (Networking.IsOwner(gameObject))
                    {
                        ReturnToAnchor();
                    }
                }
            }

            // Only track acceleration when bell is held
            if (!isHeld) return;
            if (bellEndTransform == null) return;

            // Calculate current velocity
            Vector3 currentPosition = bellEndTransform.position;
            Vector3 currentVelocity = (currentPosition - lastPosition) / Time.deltaTime;

            // Calculate acceleration
            Vector3 acceleration = (currentVelocity - lastVelocity) / Time.deltaTime;
            float accelerationMagnitude = acceleration.magnitude;

            // Apply damping curve for the first x seconds after pickup
            float timeSincePickup = Time.time - pickupTime;
            if (timeSincePickup < dampingDuration)
            {
                float normalizedTime = timeSincePickup / dampingDuration;
                float dampingMultiplier = dampingCurve.Evaluate(normalizedTime);
                accelerationMagnitude *= dampingMultiplier;
            }

            // Check if acceleration exceeds threshold
            if (accelerationMagnitude >= accelerationThreshold)
            {
                // Check cooldown
                if (Time.time - lastRingTime >= cooldown)
                {
                    // Trigger the networked ring (plays sound and particles on all clients)
                    TryRingBell();
                }
            }

            // Update tracking values for next frame
            lastPosition = currentPosition;
            lastVelocity = currentVelocity;
        }

        /// <summary>
        /// Returns the bell to its anchor position after being dropped.
        /// </summary>
        private void ReturnToAnchor()
        {
            if (objectSync != null)
            {
                objectSync.TeleportTo(returnAnchor);
            }
            bellTransform.position = returnAnchor.position;
            bellTransform.rotation = returnAnchor.rotation;
            lastDropTime = -1f;
        }

        /// <summary>
        /// Attempt to ring the bell. Checks cooldown and broadcasts event if valid.
        /// Called when acceleration threshold is exceeded while held.
        /// </summary>
        public void TryRingBell()
        {
            // Check cooldown
            if (Time.time - lastRingTime < cooldown)
            {
                return;
            }

            // Validate HatManager
            if (hatManager == null)
            {
                Debug.LogError("[HatBell] HatManager not found!");
                return;
            }

            // Update cooldown
            lastRingTime = Time.time;

            // Play bell sound and emit particles on all clients
            SendCustomNetworkEvent(NetworkEventTarget.All, nameof(PlayBellEffects));

            // Broadcast the event to all HatBell instances
            string triggerName = localPlayer != null ? localPlayer.displayName : "Unknown";
            hatManager.SendCustomNetworkEvent(NetworkEventTarget.All, nameof(HatManager.OnHatEvent), targetHatTypeId, triggerName);

            Debug.Log($"[HatBell] Bell rung by {triggerName}, targeting hat type {targetHatTypeId}");
        }

        /// <summary>
        /// Plays the bell sound and emits particles. Called via SendCustomNetworkEvent.
        /// </summary>
        public void PlayBellEffects()
        {
            // Play local bell sound (normal spatial audio)
            if (localBellSound != null)
            {
                localBellSound.Play();
            }

            // Emit particles
            if (soundParticles != null)
            {
                soundParticles.Play();
            }
        }

        public override void OnHatEvent(byte hatTypeId, string triggerPlayerName)
        {
            if (hatManager == null) return;
            if (localPlayer == null) return;

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

            // Check if local player has a hat
            if (!hatManager.PlayerHasHats[localPlayerId])
            {
                return;
            }

            // Check if hat type matches (255 = wildcard, matches any hat)
            byte myHatType = hatManager.PlayerHatTypes[localPlayerId];
            bool hatTypeMatches = (hatTypeId == 255) || (myHatType == hatTypeId);
            if (!hatTypeMatches)
            {
                return;
            }

            // Check if the trigger player is the one who gave us this hat
            if (onlyTriggerForGiver)
            {
                string myGiverName = hatManager.PlayerGiverNames[localPlayerId];
                bool giverMatches = !string.IsNullOrEmpty(myGiverName) && myGiverName == triggerPlayerName;
                if (!giverMatches)
                {
                    return;
                }
            }

            // All conditions met - play the event sound (configured with large near radius for global hearing)
            if (eventBellSound != null)
            {
                eventBellSound.Play();
            }

            Debug.Log($"[HatBell] Received matching event from {triggerPlayerName} for hat type {hatTypeId}");
        }

        public override void OnHatInitialLoad(byte hatTypeId, string triggerPlayerName)
        {
            // Use the same logic as OnHatEvent - check if this bell should respond
            // to the initial hat load for the local player
            if (hatManager == null) return;
            if (localPlayer == null) return;

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

            // Check if local player has a hat
            if (!hatManager.PlayerHasHats[localPlayerId])
            {
                return;
            }

            // Check if hat type matches (255 = wildcard, matches any hat)
            byte myHatType = hatManager.PlayerHatTypes[localPlayerId];
            bool hatTypeMatches = (hatTypeId == 255) || (myHatType == hatTypeId);
            if (!hatTypeMatches)
            {
                return;
            }

            // Check if the trigger player is the one who gave us this hat
            if (onlyTriggerForGiver)
            {
                string myGiverName = hatManager.PlayerGiverNames[localPlayerId];
                bool giverMatches = !string.IsNullOrEmpty(myGiverName) && myGiverName == triggerPlayerName;
                if (!giverMatches)
                {
                    return;
                }
            }

            // All conditions met - but do NOT play event sound on initial load.
            // The bell sound should only play when someone actively rings it.
            // Keep the log for debugging purposes.
            Debug.Log($"[HatBell] Received initial load event from {triggerPlayerName} for hat type {hatTypeId}");
        }

        public override void OnHatRemoved(byte hatTypeId, string triggerPlayerName)
        {
            
        }

        /// <summary>
        /// Programmatically ring the bell (e.g., from another script)
        /// </summary>
        public void RingBell()
        {
            TryRingBell();
        }

        /// <summary>
        /// Check if the bell is currently on cooldown
        /// </summary>
        public bool IsOnCooldown()
        {
            return Time.time - lastRingTime < cooldown;
        }

        /// <summary>
        /// Get remaining cooldown time in seconds
        /// </summary>
        public float GetRemainingCooldown()
        {
            float remaining = cooldown - (Time.time - lastRingTime);
            return remaining > 0 ? remaining : 0f;
        }
    }
}
