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

public class GrabbableHand : UdonSharpBehaviour
{

    public VRC_Pickup pickup;
    public HoldemPlayer player;

    public Transform desktopExactGrip;
    public Collider targetCollider;

    public PlayingCard hole0;
    public PlayingCard hole1;
    public GameObject eyeUi;

    public Transform forceShowTransform;
    public Transform finalShowPivot;
    public Transform finalShowTransform;

    //VRCObjectSync objectSync;
    public SmartObjectSync objectSync;
    public Transform initialTransform;
    public Rigidbody rb;
    public Transform cardCenter;

    private bool canFold = false;
    private bool isHeld = false;
    private Vector3 lastPosition;
    private VRC_Pickup.PickupHand holdingHand = VRC_Pickup.PickupHand.None;

    [UdonSynced] public bool isVisibleToOthers = false;

    public bool IsFolded()
    {
        // avoid redundant checks for all players.
        if (!Networking.IsOwner(gameObject) || !canFold)
            return false;

        if (targetCollider == null)
            return false;

        // if its moving, cant fold.
        if (lastPosition == null)
            return false;
        
        Vector3 delta = transform.position - lastPosition;
        float sqrSpeed = delta.sqrMagnitude / (Time.deltaTime * Time.deltaTime);
        //Debug.Log($"sqrSpeed: {sqrSpeed}, delta: {Time.deltaTime}");
        lastPosition = transform.position;


        if (sqrSpeed >= (0.001f * 0.001f))
            return false;

        // Check collision
        Vector3 point = cardCenter != null ? cardCenter.position : 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
        return (closest - point).sqrMagnitude < 0.001f;
    }

    void Start()
    {
        // Store initial transform state
        initialTransform.position = transform.position;
        initialTransform.rotation = transform.rotation;
        lastPosition = initialTransform.position;

        // Enable AutoHold only for Desktop users
        if (!Networking.LocalPlayer.IsUserInVR())
        {
            pickup.AutoHold = VRC_Pickup.AutoHoldMode.Yes;
            // Desktop: use Grip mode with exact transform
            pickup.orientation = VRC_Pickup.PickupOrientation.Grip;
            pickup.ExactGrip = desktopExactGrip;
        }
        else
        {
            pickup.AutoHold = VRC_Pickup.AutoHoldMode.No;
            // VR: use Any mode with no exact grip
            pickup.orientation = VRC_Pickup.PickupOrientation.Any;
            pickup.ExactGrip = null;
        }
    }

    public void SetEnabled(bool visible)
    {
        hole0.SetVisible(visible);
        hole1.SetVisible(visible);
        if (!visible)
            MakeUngrabbable();
    }
    public override void OnPickup()
    {
        Networking.SetOwner(Networking.LocalPlayer, gameObject);

        canFold = false;
        isHeld = true;
        holdingHand = pickup.currentHand;
    }

    public override void OnDrop()
    {
        canFold = true;
        isHeld = false; // Fix: should be false when dropped
        holdingHand = VRC_Pickup.PickupHand.None;
    }

    public override void InputUse(bool value, UdonInputEventArgs args)
    {
        // VR: trigger pressed while holding
        if (Networking.LocalPlayer.IsUserInVR() && isHeld && value)
        {
            // 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)
            {
                Debug.Log("VR trigger pressed while holding!");
                FlipVisibleToOthers();
            }
        }
    }

    // Desktop: AutoHold enabled, respond when use button pressed while holding
    public override void OnPickupUseDown()
    {
        if (!Networking.LocalPlayer.IsUserInVR() && isHeld)
        {
            Debug.Log("Desktop use pressed while holding!");
            FlipVisibleToOthers();
        }
    }

    public void ForceToShowPosition()
    {
        pickup.Drop();

        TransformMoverUdon mover = GetComponent<TransformMoverUdon>();
        if (mover != null && mover.enabled) return; // dont want to run twice

        //objectSync.FlagDiscontinuity();
        transform.position = forceShowTransform.position;
        transform.rotation = forceShowTransform.rotation;

        if (Networking.IsOwner(gameObject))
        {
            /*objectSync.TeleportTo(forceShowTransform.position, forceShowTransform.rotation, Vector3.zero, Vector3.zero);
            objectSync.rigid.velocity = Vector3.zero;
            objectSync.rigid.angularVelocity = Vector3.zero;
            */
            objectSync.Respawn();
            objectSync.enabled = false;
            RequestSerialization();
        }
        
        // Get player head position
        VRCPlayerApi player = Networking.LocalPlayer;

        if (player != null)
        {
            Vector3 playerPos = player
                .GetTrackingData(VRCPlayerApi.TrackingDataType.Head)
                .position;

            // Compute horizontal direction to player
            Vector3 directionToPlayer = playerPos - finalShowPivot.position;
            directionToPlayer.y = 0f; // horizontal plane only

            // Determine original distance from pivot to final position
            float distance = Vector3.Distance(
                forceShowTransform.position,
                finalShowPivot.position
            );

            // Set final position along direction toward player, keeping distance
            if (directionToPlayer.sqrMagnitude > 0.001f)
            {
                finalShowTransform.position =
                    finalShowPivot.position +
                    directionToPlayer.normalized * distance;

                // Compute rotation to face player
                Quaternion lookRotation =
                    Quaternion.LookRotation(directionToPlayer, Vector3.up);

                // If forward is X, rotate -90° around Y
                lookRotation *= Quaternion.Euler(0f, -90f, 0f);

                // Preserve original local Z rotation (roll)
                Vector3 euler = lookRotation.eulerAngles;
                euler.z = finalShowTransform.localEulerAngles.z;

                finalShowTransform.rotation = Quaternion.Euler(euler);
            }
        }

        if (mover != null)
        {
            mover.SetStartAndTarget(forceShowTransform, finalShowTransform);
            mover.enabled = true;
        }
    }

    public void MakeInvisibleToOthers()
    {
        if (Networking.IsOwner(gameObject))
        {
            isVisibleToOthers = false;
            RequestSerialization();
            OnDeserialization();
        }
    }

    private void FlipVisibleToOthers()
    {
        isVisibleToOthers = !isVisibleToOthers;
        RequestSerialization();
        OnDeserialization();
    }

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

    public void MoveBackToInitialPosition()
    {
        //objectSync.FlagDiscontinuity();
        //transform.position = initialPosition;
        //transform.rotation = initialRotation;
        TransformMoverUdon mover = GetComponent<TransformMoverUdon>();
        transform.position = initialTransform.position;
        transform.rotation = initialTransform.rotation;
        if (mover != null) mover.SetStartAndTarget(initialTransform, initialTransform); // networking... my beloathed...
        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;
            */
            objectSync.enabled = true; 
            RequestSerialization();
        }
        canFold = false;

        if (mover != null) mover.enabled = false;
    }

    public void MakeUngrabbable()
    {
        // Disable pickup
        if (pickup != null)
        {
            pickup.pickupable = false;
            pickup.Drop();
        }
        if (rb != null)
        {
            //rb.isKinematic = true;
            //rb.useGravity = false;
        }
    }

    public void SetCards(int hole0Id, int hole1Id)
    {
        if (hole0 != null)
            hole0.SetCardId(hole0Id);
        if (hole1 != null)
            hole1.SetCardId(hole1Id);
    }

    public void MakeGrabbable()
    {
        // Enable pickup
        if (pickup != null)
        {
            pickup.pickupable = true;
        }
        if (rb != null)
        {
            rb.isKinematic = false;
            rb.useGravity = true;
        }
    }

    // RIP: perfect streak of writing code without any networking.
    // we determining the ownership from whether or not the card is pickupable.
    // otherwise, we risk bugs after seat switches

    // Note: isVisibleToOthers is checked on HoldemPlayer's side.
    // unfortunately, there are lots of state we depend on to actually change this card display.
    private void OnDeserialization()
    {
        if (pickup == null)
        {
            Debug.LogError("[GrabbableHand] Pickup is null! Can't determine owner");
            return;
        }

        if (eyeUi == null)
        {
            Debug.LogWarning("[GrabbableHand] eyeUi is null!");
        }
        else
        {
            bool showEye = isVisibleToOthers && pickup.pickupable;
            Debug.Log($"[GrabbableHand] eyeUi setActive: {showEye}");
            eyeUi.SetActive(isVisibleToOthers && pickup.pickupable);
        }
        
        player.UpdateCardDisplay();
    }
}
