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("Maximum distance to detect another player's hand")]
    public float detectionRadius = 0.3f;

    [Tooltip("Master-owned object that performs the transfer")]
    public HoldemAuthority authority;
        
    [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;

    [Tooltip("Seconds to wait for the master to accept a transfer before playing the fail sound")]
    public float confirmTimeoutSeconds = 2f;

    // 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;

    // Waiting for the master's donation count for this card to change
    private bool awaitingConfirmation = false;
    private int confirmBaseline;
    private int confirmDeadlineMillis;
    private int nextRequestMillis;

    // 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 (awaitingConfirmation) CheckConfirmation();

        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()
    {
        // Clicks during the cooldown or while a request is in flight are ignored
        int now = Networking.GetServerTimeInMilliseconds();
        if (awaitingConfirmation || now - nextRequestMillis < 0) return;

        // 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
        if (authority == null)
        {
            Debug.Log("[CharityCard] HoldemAuthority is not configured");
            PlayFailSound();
            return;
        }

        int senderBalanceAmount = senderBalance.GetBalance();
        int transferAmount = authority.charityTransferAmount;
        int minimumBalanceRequired = authority.charityMinimumBalanceRequired;
        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;
        }

        int cardIndex = GetCardIndex();
        if (cardIndex < 0)
        {
            Debug.Log("[CharityCard] Card is not registered with HoldemAuthority");
            PlayFailSound();
            return;
        }

        // The master re-checks the transfer, moves the chips, and bumps this card's donation
        // count; everyone plays the effects when that count changes
        confirmBaseline = authority._GetCharityDonations(cardIndex);
        confirmDeadlineMillis = now + (int)(confirmTimeoutSeconds * 1000);
        nextRequestMillis = now + (int)(authority.charityCooldownSeconds * 1000);
        awaitingConfirmation = true;

        int targetPlayerId = currentTarget.playerId;
        authority.SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(HoldemAuthority.RequestCharity), targetPlayerId, cardIndex);

        Debug.Log($"[CharityCard] Requested {transferAmount} chip transfer from {localPlayer.displayName} to {currentTarget.displayName}");
    }

    private void CheckConfirmation()
    {
        int cardIndex = GetCardIndex();
        if (cardIndex >= 0 && authority._GetCharityDonations(cardIndex) != confirmBaseline)
        {
            awaitingConfirmation = false;
            return;
        }
        if (Networking.GetServerTimeInMilliseconds() - confirmDeadlineMillis < 0) return;

        awaitingConfirmation = false;
        Debug.Log("[CharityCard] Transfer was not accepted");
        PlayFailSound();
    }

    private int GetCardIndex()
    {
        if (authority == null || authority.charityCards == null) return -1;
        CharityCard[] cards = authority.charityCards;
        for (int i = 0; i < cards.Length; i++)
        {
            if (cards[i] == this) return i;
        }
        return -1;
    }

    // Played by HoldemAuthority once the master has accepted a transfer from this card
    public void _PlayDonationEffects()
    {
        if (successSound != null)
        {
            successSound.Play();
        }
        if (successParticles != null)
        {
            successParticles.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;
    }
}
