using System;
using Conjure.GameData;
using Conjure.Items;
using Obvious.Soap;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Serialization;

namespace Conjure.Interraction
{
    
    public class PlayerInterraction : SerializedMonoBehaviour
    {
        [SerializeField, Required] private CharacterData characterData;
        [SerializeField, Required] private GameObject grabingParent;
        [SerializeField, FoldoutGroup("Debug")] private GameObject holdedObject = null;
        [SerializeField, FoldoutGroup("Debug")] private IInteractable _interractable = null;

        public void SetInterractable(IInteractable interactable)
        {
            if (_interractable != null)
            {
                return;
            }
            _interractable = interactable;
        }
        
        public void UnsetInterractable(IInteractable interactable)
        {
            if (_interractable == null || _interractable != interactable)
            {
                return;
            }

            _interractable = null;
        }
        
        public bool Grab(GameObject objectToGrab)
        {
            if (holdedObject != null)
            {
                return false;
            }

            holdedObject = objectToGrab;
            holdedObject.transform.parent = grabingParent.transform;
            holdedObject.transform.position = grabingParent.transform.position;

            if (holdedObject.TryGetComponent(out Rigidbody holdedRb))
            {
                holdedRb.velocity = Vector3.zero;
                holdedRb.isKinematic = true;
                holdedRb.detectCollisions = false;
            }
            
            return true;
        }

        public bool Drop(GameObject objectToDrop)
        {
            if (holdedObject == null || holdedObject != objectToDrop)
            {
                return false;
            }

            if (holdedObject.TryGetComponent(out Rigidbody holdedRb))
            {
                holdedRb.isKinematic = false;
                holdedRb.detectCollisions = true;
                
            }
            
            holdedObject.transform.parent = null;
            holdedObject = null;
            
            return true;
        }

        private void OnTriggerEnter(Collider other)
        {
            InterractableElement interactable;
            if (other.gameObject.TryGetComponent(out interactable))
            {
                interactable.InterractEnter(this);
            }
        }

        public void OnInterract()
        {
            if (_interractable != null)
            {
                _interractable.Interract(this);
            }
        }
        
        private void OnTriggerLeave(Collider other)
        {
            InterractableElement interactable;
            if (other.gameObject.TryGetComponent(out interactable))
            {
                interactable.InterractLeave(this);
            }
        }
    }
}