using System;
using DG.Tweening;
using UniRx;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Sources
{
    public class CylinderBomb : MonoBehaviour
    {
        [SerializeField] private Rigidbody _rb;
        [SerializeField] private GameObject _destroyEffect;
        [SerializeField] private float _radius = 2f;

        private float _damage;
        private Transform _owner;
        private IDisposable _lifetimeTimer;
        
        private void Awake()
        {
            _destroyEffect.SetActive(false);
        }

        public void RandomShoot(float damage, float radius, float flyDuration, Transform owner)
        {
            _damage = damage;
            _owner = owner;

            var direction = Random.insideUnitSphere * radius;
            direction.y = 10000;
            
            _rb.AddForce(direction);
            
            _lifetimeTimer = Observable.Timer(TimeSpan.FromSeconds(10)).Subscribe(_ => Destroy(gameObject));
        }

        private void OnCollisionEnter(Collision other)
        {
            var players = Physics.OverlapSphere(transform.position, 2f, LayerMask.GetMask("Player"));
            foreach (var potentialPlayer in players)
            {
                var damageable = potentialPlayer.GetComponentInParent<IDamageable>();
                damageable?.TakeDamage(_damage, _owner, DamageType.Ranged);
            }
            
            Die();
        }

        private void Die()
        {
            _lifetimeTimer?.Dispose();
            Destroy(_rb);
            _destroyEffect.SetActive(true);
            
            DOTween.Sequence().Insert(2f, transform.DOScale(0, 0.5f)).OnComplete(() => Destroy(gameObject));
        }
    }
}