using System;
using UnityEngine;

namespace Infrastructure.Unity
{
    public class TeleporterAdapter : MonoBehaviour
    {
        public event Action OnTeleport;
        
        private Transform _targetDestination;
        private TeleporterAdapter _targetAdapter;
        private float _cooldownTimer;
        
        public void Initialize(Transform target)
        {
            _targetDestination = target;
            _targetAdapter = target.GetComponent<TeleporterAdapter>();
        }

        private void Update()
        {
            if (_cooldownTimer > 0f)
            {
                _cooldownTimer -= Time.deltaTime;
            }
        }

        public void Lock(float duration)
        {
            _cooldownTimer = duration;
        }

        private void OnTriggerEnter(Collider other)
        {
            if (!_targetDestination) return;
            if (_cooldownTimer > 0f) return;
            
            if (other.TryGetComponent<PlayerController>(out var player))
            {
                var dest = _targetDestination.position;
                player.transform.position = dest + Vector3.up * 1.0f;
                player.Rigidbody.linearVelocity = Vector3.zero;

                if (_targetAdapter)
                {
                    _targetAdapter.Lock(1.0f); 
                }
                
                Lock(1.0f);
                OnTeleport?.Invoke();
            }
        }
        
        private void OnDrawGizmos()
        {
            if (_targetDestination)
            {
                Gizmos.color = Color.magenta;
                Gizmos.DrawLine(transform.position, _targetDestination.position);
            }
        }
    }
}
