﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

namespace UdonChipsHat
{
    /// <summary>
    /// A hat that caps the wearer's avatar size to a configurable maximum.
    /// When the hat is applied, the player's avatar eye height is limited.
    /// When the hat is removed, the original size is restored.
    /// </summary>
    [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
    public class HatGremlifier : HatEventSubscriber
    {
        [Header("Hat Manager")]
        [Tooltip("Reference to HatManager")]
        public HatManager hatManager;

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

        [Tooltip("Maximum eye height in meters (default 0.8). Set to 0 to disable size capping.")]
        public float maxEyeHeightMeters = 0.8f;

        [Tooltip("If true, prevents the player from manually changing their size while wearing the hat")]
        public bool disableManualScaling = true;

        [Tooltip("How often (in seconds) to re-apply the size cap while the hat is worn")]
        public float reapplyIntervalSeconds = 2f;

        // State
        private VRCPlayerApi localPlayer;
        private float originalEyeHeight = -1f;
        private float originalMaxEyeHeight = -1f;
        private bool wasManualScalingAllowed = true;
        private bool hasGremlifierHat = false;

        void Start()
        {
            localPlayer = Networking.LocalPlayer;

            if (hatManager == null)
            {
                Debug.LogError("[HatGremlifier] HatManager not assigned!");
                return;
            }

            // Subscribe to HatManager for events
            hatManager.Subscribe(this);

            // Start periodic reapply loop
            SendCustomEventDelayedSeconds(nameof(_PeriodicReapply), reapplyIntervalSeconds);
        }

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

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

            // Check if local player has a hat
            if (!hatManager.PlayerHasHats[localPlayerId])
            {
                // Hat was removed - restore original size if we had the gremlifier
                if (hasGremlifierHat)
                {
                    RestoreOriginalSize();
                    hasGremlifierHat = false;
                }
                return;
            }

            // Check if hat type matches (255 = wildcard, matches any hat)
            bool hatTypeMatches = (targetHatTypeId == 255) || (hatTypeId == targetHatTypeId);
            if (!hatTypeMatches)
            {
                return;
            }

            // Apply size cap if not already applied
            if (!hasGremlifierHat)
            {
                ApplySizeCap();
                hasGremlifierHat = true;
            }
        }

        public override void OnHatInitialLoad(byte hatTypeId, string triggerPlayerName)
        {
            if (hatManager == null) return;
            if (localPlayer == null || !localPlayer.IsValid()) 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)
            bool hatTypeMatches = (targetHatTypeId == 255) || (hatTypeId == targetHatTypeId);
            if (!hatTypeMatches)
            {
                return;
            }

            // Apply size cap on initial load
            ApplySizeCap();
            hasGremlifierHat = true;

            Debug.Log($"[HatGremlifier] Applied size cap on initial load. Max eye height: {maxEyeHeightMeters}m");
        }

        /// <summary>
        /// Applies the size cap to the local player.
        /// Stores original size and disables manual scaling if configured.
        /// Sets a hard maximum eye height limit via SetAvatarEyeHeightMaximumByMeters.
        /// </summary>
        private void ApplySizeCap()
        {
            if (localPlayer == null || !localPlayer.IsValid()) return;
            if (maxEyeHeightMeters <= 0) return;

            // Store original eye height if not already stored
            if (originalEyeHeight < 0)
            {
                originalEyeHeight = localPlayer.GetAvatarEyeHeightAsMeters();
                Debug.Log($"[HatGremlifier] Stored original eye height: {originalEyeHeight}m");
            }

            // Store original maximum eye height if not already stored
            if (originalMaxEyeHeight < 0)
            {
                originalMaxEyeHeight = localPlayer.GetAvatarEyeHeightMaximumAsMeters();
                Debug.Log($"[HatGremlifier] Stored original max eye height: {originalMaxEyeHeight}m");
            }

            // Store manual scaling preference
            wasManualScalingAllowed = localPlayer.GetManualAvatarScalingAllowed();

            // Set hard maximum eye height limit - this prevents players from exceeding it
            localPlayer.SetAvatarEyeHeightMaximumByMeters(maxEyeHeightMeters);
            Debug.Log($"[HatGremlifier] Set maximum eye height to {maxEyeHeightMeters}m");

            // Disable manual scaling to enforce the cap
            if (disableManualScaling)
            {
                localPlayer.SetManualAvatarScalingAllowed(false);
            }

            // Apply the size cap if current height exceeds max
            float currentEyeHeight = localPlayer.GetAvatarEyeHeightAsMeters();
            if (currentEyeHeight > maxEyeHeightMeters)
            {
                localPlayer.SetAvatarEyeHeightByMeters(maxEyeHeightMeters);
                Debug.Log($"[HatGremlifier] Capped eye height from {currentEyeHeight}m to {maxEyeHeightMeters}m");
            }
            else
            {
                Debug.Log($"[HatGremlifier] Current eye height {currentEyeHeight}m is already within cap of {maxEyeHeightMeters}m");
            }
        }

        /// <summary>
        /// Restores the original size and manual scaling settings.
        /// Called when the hat is removed.
        /// </summary>
        private void RestoreOriginalSize()
        {
            if (localPlayer == null || !localPlayer.IsValid()) return;

            // Restore manual scaling
            localPlayer.SetManualAvatarScalingAllowed(wasManualScalingAllowed);

            // Restore original maximum eye height if we have a valid stored value
            if (originalMaxEyeHeight >= 0)
            {
                localPlayer.SetAvatarEyeHeightMaximumByMeters(originalMaxEyeHeight);
                Debug.Log($"[HatGremlifier] Restored original max eye height: {originalMaxEyeHeight}m");
            }

            // Restore original eye height if we have a valid stored value
            if (originalEyeHeight > 0)
            {
                localPlayer.SetAvatarEyeHeightByMeters(originalEyeHeight);
                Debug.Log($"[HatGremlifier] Restored original eye height: {originalEyeHeight}m");
            }

            // Reset stored values
            originalEyeHeight = -1f;
            originalMaxEyeHeight = -1f;
            hasGremlifierHat = false;
        }

        /// <summary>
        /// Called when the hat is removed from the local player.
        /// Restores original size settings.
        /// </summary>
        public override void OnHatRemoved(byte hatTypeId, string triggerPlayerName)
        {
            // Only restore if we had the gremlifier hat active
            if (!hasGremlifierHat) return;

            // Check if the removed hat type matches our target
            bool hatTypeMatches = (targetHatTypeId == 255) || (hatTypeId == targetHatTypeId);
            if (!hatTypeMatches) return;

            RestoreOriginalSize();
            Debug.Log($"[HatGremlifier] Hat removed. Restored original size settings.");
        }

        /// <summary>
        /// Called when the local player's avatar changes.
        /// Re-applies the size cap if the player is wearing the gremlifier hat.
        /// </summary>
        public override void OnAvatarChanged(VRCPlayerApi player)
        {
            if (!hasGremlifierHat) return;
            if (player == null || !player.IsValid()) return;
            if (!player.isLocal) return;

            // Re-apply size cap after avatar change
            // Use a slight delay to ensure the avatar has finished loading
            SendCustomEventDelayedSeconds(nameof(ReapplySizeCap), 1f);
        }

        /// <summary>
        /// Called when the local player's avatar eye height changes.
        /// Re-applies all size cap restrictions if the player is wearing the gremlifier hat.
        /// </summary>
        public override void OnAvatarEyeHeightChanged(VRCPlayerApi player, float newHeight)
        {
            if (!hasGremlifierHat) return;
            if (player == null || !player.IsValid()) return;
            if (!player.isLocal) return;
            if (maxEyeHeightMeters <= 0) return;

            // Re-apply the hard maximum limit and manual scaling block (safety net)
            localPlayer.SetAvatarEyeHeightMaximumByMeters(maxEyeHeightMeters);
            if (disableManualScaling)
            {
                localPlayer.SetManualAvatarScalingAllowed(false);
            }

            // If the new height exceeds our cap, clamp it
            if (newHeight > maxEyeHeightMeters)
            {
                player.SetAvatarEyeHeightByMeters(maxEyeHeightMeters);
                Debug.Log($"[HatGremlifier] Re-applied restrictions. Height changed to {newHeight}m, capped to {maxEyeHeightMeters}m");
            }
        }

        /// <summary>
        /// Re-applies the size cap. Called via SendCustomEventDelayedSeconds.
        /// Fully re-applies max eye height limit, manual scaling block, and caps current height.
        /// </summary>
        public void ReapplySizeCap()
        {
            if (!hasGremlifierHat) return;
            if (localPlayer == null || !localPlayer.IsValid()) return;
            if (maxEyeHeightMeters <= 0) return;

            // Re-apply the hard maximum height limit (resets when avatar changes)
            localPlayer.SetAvatarEyeHeightMaximumByMeters(maxEyeHeightMeters);
            Debug.Log($"[HatGremlifier] Re-applied max eye height limit to {maxEyeHeightMeters}m");

            // Re-apply manual scaling restriction (resets when avatar changes)
            if (disableManualScaling)
            {
                localPlayer.SetManualAvatarScalingAllowed(false);
                Debug.Log("[HatGremlifier] Re-applied manual scaling restriction");
            }

            // Cap current height if it exceeds the max
            float currentEyeHeight = localPlayer.GetAvatarEyeHeightAsMeters();
            if (currentEyeHeight > maxEyeHeightMeters)
            {
                localPlayer.SetAvatarEyeHeightByMeters(maxEyeHeightMeters);
                Debug.Log($"[HatGremlifier] Re-applied size cap after avatar change. Capped from {currentEyeHeight}m to {maxEyeHeightMeters}m");
            }
        }

        /// <summary>
        /// Periodic loop that re-applies the size cap every reapplyIntervalSeconds.
        /// Ensures the cap is re-applied even if the player resets their height
        /// via VRChat's built-in reset (which may not fire OnAvatarEyeHeightChanged).
        /// </summary>
        public void _PeriodicReapply()
        {
            // Re-schedule regardless of hat state to keep the loop alive
            SendCustomEventDelayedSeconds(nameof(_PeriodicReapply), reapplyIntervalSeconds);

            if (!hasGremlifierHat) return;

            ReapplySizeCap();
        }

        void OnDestroy()
        {
            // Restore original size if the object is destroyed while hat is active
            if (hasGremlifierHat)
            {
                RestoreOriginalSize();
            }
        }
    }
}