using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using MMMaellon;

public class GrabbablePile : UdonSharpBehaviour
{
    public VRC_Pickup pickup;
    public HoldemPlayer player;
    public Collider targetCollider;
    public AudioPoolPlayer chipClinkPlayer;
    public Transform initialTransform;
    public Collider ownCollider;

    private SmartObjectSync objectSync;
    private Rigidbody rb;
    private bool physicalBettingEnabled;
    private bool physicalGrabbable;
    private bool trackingCollision;
    private int dropToken;
    private int pendingReturnToken;
    private bool callActionActive;

    private void Start()
    {
        objectSync = GetComponent<SmartObjectSync>();
        rb = GetComponent<Rigidbody>();
        if (pickup != null && Networking.LocalPlayer != null && !Networking.LocalPlayer.IsUserInVR())
            pickup.AutoHold = VRC_Pickup.AutoHoldMode.Yes;
        if (initialTransform != null)
        {
            initialTransform.position = transform.position;
            initialTransform.rotation = transform.rotation;
        }
    }

private void Update()
    {
        if ((!callActionActive && !trackingCollision) || targetCollider == null || player == null) return;
        Vector3 point = transform.position;
        if ((targetCollider.ClosestPoint(point) - point).sqrMagnitude >= 0.001f) return;

        bool committed = physicalBettingEnabled ? CommitPhysicalCall() : CommitLegacy();
        if (!committed) return;
        trackingCollision = false;
        callActionActive = false;
        player.SetPhysicalCallActionActive(false);
        SetPickupable(false);
        if (pickup != null && pickup.IsHeld) pickup.Drop();
        DisablePhysics();
        PokerChipPile pile = GetComponent<PokerChipPile>();
        if (pile != null) pile.SetTextVisibility(true);
        if (pendingReturnToken != dropToken)
        {
            pendingReturnToken = dropToken;
            SendCustomEventDelayedSeconds(nameof(_MoveBackToInitialPosition), 0.5f);
        }
    }

    private bool CommitLegacy()
    {
        player._UiConfirmImmediately();
        return true;
    }

private bool CommitPhysicalCall()
    {
        if (player.physicalRaisePile != null) player.physicalRaisePile._CancelReservationForCall();
        // The stored bet can be stale (e.g. a reservation that changed it); a call always commits the current call amount.
        player._ResetPhysicalBetToCall();
        if (!player._CommitPhysicalBet()) return false;
        if (player.game != null) player.game.CollectCommittedChips(player);
        return true;
    }

    public override void Interact()
    {
        if (player == null) return;

        if (physicalBettingEnabled)
        {
            return;
        }

        if (Networking.LocalPlayer != null && Networking.LocalPlayer.IsUserInVR()) return;

        CommitLegacy();
    }


    public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner)
    {
        if (!Utilities.IsValid(requestingPlayer) || !Utilities.IsValid(requestedOwner)) return false;
        if (requestingPlayer.playerId != requestedOwner.playerId) return false;
        if (HoldemAuthority.IsAuthority(requestingPlayer)) return true;
        return player != null && player.IsSeated() && Networking.IsOwner(requestingPlayer, player.gameObject);
    }

    public override void OnPickup()
    {
        if (Networking.LocalPlayer != null) Networking.SetOwner(Networking.LocalPlayer, gameObject);
        PokerChipPile pile = GetComponent<PokerChipPile>();
        if (pile != null) pile.SetTextVisibility(false);
        if (chipClinkPlayer != null) chipClinkPlayer.Play();

        if (physicalBettingEnabled)
        {
            dropToken++;
            if (!physicalGrabbable || Networking.LocalPlayer == null
                || player == null || !player.CanUsePhysicalBetting())
            {
                if (pile != null) pile.SetTextVisibility(true);
                if (pickup != null) pickup.Drop();
                return;
            }
            callActionActive = true;
            player.SetPhysicalCallActionActive(true);
        }
        else if (Networking.LocalPlayer != null && !Networking.LocalPlayer.IsUserInVR())
        {
            if (pickup != null) pickup.Drop();
            if (player != null) player._UiConfirmImmediately();
            return;
        }
        EnablePhysics();
    }

    public override void OnDrop()
    {
        if (physicalBettingEnabled && !callActionActive) return;
        if (chipClinkPlayer != null) chipClinkPlayer.Play();
        SetPickupable(false);
        EnablePhysics();
        trackingCollision = true;
        pendingReturnToken = ++dropToken;
        SendCustomEventDelayedSeconds(nameof(_MoveBackToInitialPosition), 0.5f);
    }

    public void _MoveBackToInitialPosition()
    {
        if (pendingReturnToken != dropToken) return;
        trackingCollision = false;
        callActionActive = false;
        DisablePhysics();
        PokerChipPile pile = GetComponent<PokerChipPile>();
        if (pile != null) pile.SetTextVisibility(true);
        if (Networking.IsOwner(gameObject) && objectSync != null) objectSync.Respawn();
        if (player != null) player.SetPhysicalCallActionActive(false);
        if (physicalBettingEnabled) SetPickupable(physicalGrabbable && player != null && player.CanUsePhysicalBetting());
    }

    public void SetGrabbable(bool grabbable)
    {
        if (physicalBettingEnabled)
        {
            SetPhysicalGrabbable(grabbable);
            return;
        }
        if (ownCollider != null) ownCollider.enabled = true;
        SetPickupable(grabbable);
        if (!grabbable && pickup != null) pickup.Drop();
    }

    public void SetPhysicalGrabbable(bool grabbable)
    {
        physicalGrabbable = grabbable;
        if (!physicalBettingEnabled || callActionActive || trackingCollision) return;
        if (ownCollider != null) ownCollider.enabled = grabbable;
        SetPickupable(grabbable);
    }

    public void SetPhysicalBettingEnabled(bool enabled)
    {
        if (physicalBettingEnabled == enabled) return;
        dropToken++;
        trackingCollision = false;
        callActionActive = false;
        if (pickup != null && pickup.IsHeld) pickup.Drop();
        physicalBettingEnabled = enabled;
        DisablePhysics();
        if (player != null) player.SetPhysicalCallActionActive(false);
        if (ownCollider != null) ownCollider.enabled = !enabled;
        SetPickupable(!enabled);
        PokerChipPile pile = GetComponent<PokerChipPile>();
        if (pile != null) pile.SetTextVisibility(true);
        if (Networking.IsOwner(gameObject) && objectSync != null) objectSync.Respawn();
    }

    public void _ResetPhysicalBetToCallDisplay()
    {
        dropToken++;
        trackingCollision = false;
        callActionActive = false;
        if (pickup != null && pickup.IsHeld) pickup.Drop();
        DisablePhysics();
        PokerChipPile pile = GetComponent<PokerChipPile>();
        if (pile != null) pile.SetTextVisibility(true);
        if (Networking.IsOwner(gameObject) && objectSync != null) objectSync.Respawn();
        if (player != null) player.SetPhysicalCallActionActive(false);
    }

    private void EnablePhysics()
    {
        if (rb != null)
        {
            rb.useGravity = true;
            rb.isKinematic = false;
        }
        if (ownCollider != null)
        {
            ownCollider.enabled = true;
            ownCollider.isTrigger = false;
        }
    }

    private void DisablePhysics()
    {
        if (rb != null)
        {
            rb.useGravity = false;
            rb.isKinematic = true;
            rb.velocity = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
        }
        if (ownCollider != null) ownCollider.isTrigger = true;
    }

    private void SetPickupable(bool value)
    {
        DisableInteractive = physicalBettingEnabled || !value;
        InteractionText = physicalBettingEnabled ? "Call" : "Bet";
        if (objectSync != null) objectSync.pickupable = value;
        else if (pickup != null) pickup.pickupable = value;
    }
}
