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

[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class DunceCapItem : UdonSharpBehaviour
{
    [Header("Configuration")]
    [Tooltip("Amount of chips it costs to use")]
    public int costAmount = 10000;
    
    [Tooltip("Amount of chips target receives")]
    public int rewardAmount = 5000;
    
    [Tooltip("Maximum distance to detect another player")]
    public float detectionRadius = 1.0f;
        
    [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 success")]
    public AudioPoolPlayer successSound;
    
    [Tooltip("Sound to play on fail")]
    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 VRCObjectSync objectSync;
    private float lastDropTime = -1f;

    void Start()
    {
        objectSync = GetComponent<VRCObjectSync>();
        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 players while holding
            FindTargetPlayer();
            return;
        }
        
        // Return to anchor after not being held for the configured delay
        if (returnAnchor != null && returnDelay >= 0f && lastDropTime >= 0f)
        {
            if (Time.time - lastDropTime >= returnDelay)
            {
                if (Networking.IsOwner(gameObject))
                {
                    objectSync.TeleportTo(returnAnchor);
                    transform.position = returnAnchor.position;
                    transform.rotation = returnAnchor.rotation;
                    lastDropTime = -1f; // Reset to prevent repeated teleports
                }
            }
        }
    }

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

        isHeld = true;
        if (pickup != null) {
            holdingHand = pickup.currentHand;
        }
        currentTarget = null;
        lastDropTime = -1f; // Reset drop timer when picked up
    }

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

    public override void OnPickupUseDown()
    {
        if (!localPlayer.IsUserInVR() && isHeld)
        {
            TryPlaceCap();
        }
    }

    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)
        {
            TryPlaceCap();
        }
    }

    private void FindTargetPlayer()
    {
        currentTarget = null;
        
        if (localPlayer == null) return;

        VRCPlayerApi[] players = new VRCPlayerApi[VRCPlayerApi.GetPlayerCount()];
        VRCPlayerApi.GetPlayers(players);

        float closestDistance = detectionRadius;

        foreach (VRCPlayerApi player in players)
        {
            if (player == null || player.isLocal) continue;

            Vector3 headPos = player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head).position;
            float dist = Vector3.Distance(transform.position, headPos);

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

    private void TryPlaceCap()
    {
        // Validate we have a target
        if (currentTarget == null)
        {
            Debug.Log("[DunceCapItem] No target player in range");
            PlayFailSound();
            return;
        }

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

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

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

        // Check if the target already has a Dunce Cap (no stacking (for now ;D))
        if (targetBalance.HasDunceCapSynced)
        {
            Debug.Log("[DunceCapItem] Target already has a Dunce Cap!");
            PlayFailSound();
            return;
        }

        // Perform the transaction
        senderBalance.ModifyBalance(-costAmount);
        targetBalance.ModifyBalance(rewardAmount);
        
        // Apply the cap
        targetBalance.ApplyDunceCap();

        Debug.Log($"[DunceCapItem] Placed Dunce Cap on {currentTarget.displayName} for {costAmount} chips");
        
        SendCustomNetworkEvent(NetworkEventTarget.All, nameof(PlaySuccessSound));
        SendCustomNetworkEvent(NetworkEventTarget.All, nameof(PlaySuccessParticles));
    }

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

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

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

    public VRCPlayerApi GetCurrentTarget()
    {
        return currentTarget;
    }

    public bool IsBeingHeld()
    {
        return isHeld;
    }
}