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

/// <summary>
/// A special card that allows players to transfer chips to other players.
/// When held near another player's hand and trigger is pressed, transfers chips.
/// </summary>
[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class CharityCard : UdonSharpBehaviour
{
    [Header("Configuration")]
    [Tooltip("Amount of chips to transfer per use")]
    public int transferAmount = 1000;
    
    [Tooltip("Minimum balance required to send chips (sender must have this + transfer amount)")]
    public int minimumBalanceRequired = 5000;
    
    [Tooltip("Maximum distance to detect another player's hand")]
    public float detectionRadius = 0.3f;
        
    [Header("Return to Anchor")]
    [Tooltip("Transform to return to after not being held (set to null to disable)")]
    public Transform returnAnchor;
    
    [Tooltip("Seconds to wait after dropping before returning to anchor (-1 to disable auto-return)")]
    public float returnDelay = 5f;
    
    [Header("Audio Feedback")]
    [Tooltip("Sound to play on successful transfer")]
    public AudioPoolPlayer successSound;
    
    [Tooltip("Sound to play when transfer fails")]
    public AudioPoolPlayer failSound;

    // Visual Effects
    private ParticleSystem successParticles;

    // State tracking
    private bool isHeld = false;
    private VRC_Pickup.PickupHand holdingHand = VRC_Pickup.PickupHand.None;
    private VRCPlayerApi currentTarget = null;
    private VRCPlayerApi localPlayer;
    private VRC_Pickup pickup;
    private SmartObjectSync objectSync;
    private float lastDropTime = -1f;

    // Cached player list for FindTargetPlayer (avoids per-frame allocation)
    private VRCPlayerApi[] _players = new VRCPlayerApi[80];
    private int _playerCount;
    private bool _playersDirty = true;

    void Start()
    {
        objectSync = GetComponent<SmartObjectSync>();
        localPlayer = Networking.LocalPlayer;
        pickup = GetComponent<VRC_Pickup>();
        successParticles = GetComponent<ParticleSystem>();
        
        // Configure AutoHold for desktop users (required for OnPickupUseDown to work)
        if (localPlayer != null && !localPlayer.IsUserInVR())
        {
            pickup.AutoHold = VRC_Pickup.AutoHoldMode.Yes;
        }
        else
        {
            pickup.AutoHold = VRC_Pickup.AutoHoldMode.No;
        }
    }

    void Update()
    {
        if (isHeld)
        {
            // Continuously check for nearby player hands while holding
            FindTargetPlayer();
            return;
        }
        
        // Return to anchor after not being held for the configured delay (periodic retry)
        if (returnAnchor != null && returnDelay >= 0f && lastDropTime >= 0f)
        {
            // Safety: never return while actually held (guards against stale isHeld)
            if (pickup != null && pickup.IsHeld) return;

            if (Time.time - lastDropTime >= returnDelay)
            {
                if (Networking.IsOwner(gameObject))
                {
                    ReturnToAnchor();
                }
                lastDropTime = Time.time; // schedule next retry
            }
        }
    }

    private void RefreshPlayers()
    {
        if (!_playersDirty) return;
        _playerCount = VRCPlayerApi.GetPlayerCount();
        VRCPlayerApi.GetPlayers(_players);
        _playersDirty = false;
    }

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

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

    public override void OnPickup()
    {
        Networking.SetOwner(Networking.LocalPlayer, gameObject);

        isHeld = true;
        holdingHand = pickup.currentHand;
        currentTarget = null;
    }

    public override void OnDrop()
    {
        isHeld = false;
        holdingHand = VRC_Pickup.PickupHand.None;
        currentTarget = null;
        lastDropTime = Time.time; // Record when card was dropped
    }

    /// <summary>
    /// Desktop: Called when use button is pressed while holding (requires AutoHold)
    /// </summary>
    public override void OnPickupUseDown()
    {
        if (!localPlayer.IsUserInVR() && isHeld)
        {
            TryTransfer();
        }
    }

    /// <summary>
    /// VR: Called when trigger is pressed while holding
    /// </summary>
    public override void InputUse(bool value, UdonInputEventArgs args)
    {
        if (!localPlayer.IsUserInVR() || !isHeld || !value) return;

        // Check if trigger is from the same hand holding the object
        bool isSameHand = (args.handType == HandType.LEFT && holdingHand == VRC_Pickup.PickupHand.Left) ||
                          (args.handType == HandType.RIGHT && holdingHand == VRC_Pickup.PickupHand.Right);

        if (isSameHand)
        {
            TryTransfer();
        }
    }

    /// <summary>
    /// Finds the nearest player whose hand is within detection range
    /// </summary>
    private void FindTargetPlayer()
    {
        currentTarget = null;
        
        if (localPlayer == null) return;

        RefreshPlayers();

        float closestDistance = detectionRadius;
        Vector3 myPos = transform.position;

        for (int i = 0; i < _playerCount; i++)
        {
            VRCPlayerApi player = _players[i];
            if (player == null || player.isLocal) continue;

            // Check both hands
            Vector3 rightHandPos = player.GetBonePosition(HumanBodyBones.RightHand);
            Vector3 leftHandPos = player.GetBonePosition(HumanBodyBones.LeftHand);

            float distRight = Vector3.Distance(myPos, rightHandPos);
            float distLeft = Vector3.Distance(myPos, leftHandPos);

            float minDist = Mathf.Min(distRight, distLeft);

            if (minDist < closestDistance)
            {
                closestDistance = minDist;
                currentTarget = player;
            }
        }
    }

    /// <summary>
    /// Attempts to transfer chips to the current target player
    /// </summary>
    private void TryTransfer()
    {
        // Validate we have a target
        if (currentTarget == null)
        {
            Debug.Log("[CharityCard] No target player in range");
            PlayFailSound();
            return;
        }

        // Get sender's balance component
        PlayerBalanceComponent senderBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(localPlayer);
        if (senderBalance == null || !senderBalance.IsReady())
        {
            Debug.Log("[CharityCard] Sender balance component not ready");
            PlayFailSound();
            return;
        }

        // Check sender has enough chips
        int senderBalanceAmount = senderBalance.GetBalance();
        if (senderBalanceAmount < minimumBalanceRequired + transferAmount)
        {
            Debug.Log($"[CharityCard] Insufficient balance. Have: {senderBalanceAmount}, Need: {minimumBalanceRequired + transferAmount}");
            PlayFailSound();
            return;
        }

        // Get target's balance component
        PlayerBalanceComponent targetBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(currentTarget);
        if (targetBalance == null || !targetBalance.IsReady())
        {
            Debug.Log("[CharityCard] Target balance component not ready");
            PlayFailSound();
            return;
        }

        // Perform the transfer
        senderBalance.ModifyBalance(-transferAmount);
        targetBalance.ModifyBalance(transferAmount);

        // Track the donation stat persistently
        senderBalance.RecordDonation();

        Debug.Log($"[CharityCard] Transferred {transferAmount} chips from {localPlayer.displayName} to {currentTarget.displayName}");
        
        PlaySuccessSound();
        PlaySuccessParticles();
        SendCustomNetworkEvent(NetworkEventTarget.Others, nameof(PlaySuccessSound));
        SendCustomNetworkEvent(NetworkEventTarget.Others, nameof(PlaySuccessParticles));
    }

    [NetworkCallable]
    public void PlaySuccessParticles()
    {
        if (successParticles != null)
        {
            successParticles.Play();
        }
    }

    [NetworkCallable]
    public void PlaySuccessSound()
    {
        if (successSound != null)
        {
            successSound.Play();
        }
    }

    private void ReturnToAnchor()
    {
        if (objectSync != null)
        {
            objectSync.Respawn();
            RequestSerialization();
        }
        // Hard fallback: directly set transform in case Respawn didn't work
        transform.position = returnAnchor.position;
        transform.rotation = returnAnchor.rotation;
    }

    private void PlayFailSound()
    {
        if (failSound != null)
        {
            failSound.Play();
        }
    }

    /// <summary>
    /// Returns the current target player (useful for UI display)
    /// </summary>
    public VRCPlayerApi GetCurrentTarget()
    {
        return currentTarget;
    }

    /// <summary>
    /// Returns whether the card is currently being held
    /// </summary>
    public bool IsBeingHeld()
    {
        return isHeld;
    }
}