using DG.Tweening;
using SpringConstrainedPickup;
using UniRx;
using UnityEngine;
using Vector3 = System.Numerics.Vector3;

public class ExtinguisherHouse : MonoBehaviour
{
    public static ExtinguisherHouse Instance { get; private set; }

    [SerializeField]
    private GameObject targetObject;
    public Collider2D myCollider;

    public BoolReactiveProperty isTargetInside = new BoolReactiveProperty(true);

    private Tween _snapTween;
    
    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
        myCollider = GetComponent<BoxCollider2D>();
        
        if(myCollider == null)
            Debug.Log("GetComponent not working");
            
        
        Observable.EveryUpdate()
            .Select(_ => IsTargetInside2D())
            .DistinctUntilChanged()
            .Subscribe(x => isTargetInside.Value = x)
            .AddTo(this);

        isTargetInside
            .Skip(1)
            .Subscribe(isInside =>
        {   
            if (isInside)
            {
                SnapBack();
            }
        });
        
    }

    public bool IsTargetInside2D()
    {
        if (!myCollider || !targetObject) return false;
        return myCollider.OverlapPoint((Vector2)targetObject.transform.position);
    }

    private void SnapBack()
    {
        if (targetObject == null) return;

        var rb = targetObject.GetComponent<Rigidbody2D>();

        rb.linearVelocity = Vector2.zero;
        rb.angularVelocity = 0;

        var pickup = targetObject.GetComponent<Pickup>();
        
        if (pickup != null)
        {
            PickupManager.Instance.springAnchor
                .GetComponent<SpringUtil>()
                .OnJointRelease();

            // Call OnDragEnd 1 second later
            DOVirtual.DelayedCall(1f, () =>
                {
                    if (pickup != null) pickup.OnDragEnd();
                }, ignoreTimeScale: false)  
                .SetTarget(pickup);         
        }
        
        // Avoid stacking multiple tweens on the same target.
        _snapTween?.Kill();

        var target = transform.position - new UnityEngine.Vector3(0, 0, 1);
        
        _snapTween = targetObject.transform
            .DOMove(target, .5f) // moves to this.gameObject position
            .SetEase(Ease.OutCubic)
            .SetTarget(targetObject); 
    }

}
