﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using VRC.SDK3.Components;
using MMMaellon;

public class GrabbablePile : UdonSharpBehaviour
{
    public VRC_Pickup pickup;
    public HoldemPlayer player;

    public Collider targetCollider;
    public AudioPoolPlayer chipClinkPlayer;

    //private VRCObjectSync objectSync;
    private SmartObjectSync objectSync;
    public Transform initialTransform;

    private Rigidbody rb;
    public Collider ownCollider;

    private bool trackingCollision = false;

    void Start()
    {
        objectSync = GetComponent<SmartObjectSync>();
        rb = GetComponent<Rigidbody>();

        initialTransform.position = transform.position;
        initialTransform.rotation = transform.rotation;
    }

    void Update()
    {
        if (trackingCollision && targetCollider != null)
        {
            // Check collision
            Vector3 point = transform.position;
            // Get the closest point on the capsule to hand position
            Vector3 closest = targetCollider.ClosestPoint(point);

            // If the squared distance is extremely small,
            // the point is inside the collider
            if ((closest - point).sqrMagnitude < 0.001f)
            {
                if (player != null) 
                {
                    player.UiConfirmImmediately();
                    trackingCollision = false;
                    //MoveBackToInitialPosition();
                }
            }
        }
    }

    public void EnablePhysics()
    {
        if (rb != null)
        {
            rb.useGravity = true;
            rb.isKinematic = false;
        }

        if (ownCollider != null)
        {
            ownCollider.isTrigger = false;
        }
    }

    public 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;
        }

    }

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

        transform.GetComponent<PokerChipPile>().SetTextVisibility(false);
        chipClinkPlayer.Play();

        // Desktop: immediately confirm and drop
        if (!Networking.LocalPlayer.IsUserInVR())
        {
            pickup.Drop();
            if (player != null)
            {
                player.UiConfirmImmediately();
            }
            return;
        }

        // VR: existing logic
        EnablePhysics();
    }

    public override void OnDrop()
    {
        chipClinkPlayer.Play();
        MakeUngrabbable();

        // just in case
        EnablePhysics();
        trackingCollision = true;

        SendCustomEventDelayedSeconds(nameof(MoveBackToInitialPosition), 0.5f);
    }

    public void MoveBackToInitialPosition()
    {
        trackingCollision = false;
        DisablePhysics();

        transform.GetComponent<PokerChipPile>().SetTextVisibility(true);

        //objectSync.FlagDiscontinuity();
        //transform.position = initialPosition;
        //transform.rotation = initialRotation;
        if (Networking.IsOwner(gameObject))
        {
            objectSync.Respawn();
            /*objectSync.TeleportTo(initialTransform.position, initialTransform.rotation, Vector3.zero, Vector3.zero);
            objectSync.rigid.velocity = Vector3.zero;
            objectSync.rigid.angularVelocity = Vector3.zero;
            */
            RequestSerialization();
        }
    }

    public void SetGrabbable(bool grabbable)
    {
        if (grabbable)
            MakeGrabbable();
        else
            MakeUngrabbable();
    }

    public void MakeUngrabbable()
    {
        if (pickup != null)
        {
            pickup.pickupable = false;
            pickup.Drop();
        }
    }

    public void MakeGrabbable()
    {
        if (pickup != null)
        {
            pickup.pickupable = true;
        }
    }
}
