using Cybe;
using Sources.Gui;
using Sources.Signals;
using UnityEngine;
using Zenject;

namespace Sources
{
    public class Level : MonoBehaviour
    {
        [SerializeField] private string Name;
        [SerializeField] public int RequiredKills;
        
        [SerializeField] private GameObject _unlockedObject;
        [SerializeField] private Transform _playerSpawnPoint;
        [SerializeField] private bool _isFinalLevel;

        [Inject] private SignalBus _bus;
        [Inject] private GuiController _gui;
        [Inject] private AudioManager _audio;

        private int _killed;
        
        public Vector3 SpawnPoint => _playerSpawnPoint.position;

        private void Start()
        {
            ProcessFinalLevel();
            
            Player.LevelsProgress.TryGetValue(Name, out _killed);
            
            _gui.SetKillsProgress(_killed, RequiredKills);
            
            if (RequiredKills > _killed)
            {
                if (_unlockedObject)
                    _unlockedObject.SetActive(false);
                _bus.Subscribe<EnemyDiedSignal>(OnEnemyKilled);
            }
            else
            {
                if (_unlockedObject)
                    _unlockedObject.SetActive(true);
            }
        }

        private void OnEnemyKilled()
        {
            _killed++;
            _gui.SetKillsProgress(_killed, RequiredKills);
            Player.LevelsProgress[Name] = _killed; 

            if (_killed >= RequiredKills)
            {
                _unlockedObject.SetActive(true);
                _bus.TryUnsubscribe<EnemyDiedSignal>(OnEnemyKilled);
            }
        }

        private void OnDestroy()
        {
            _bus.TryUnsubscribe<EnemyDiedSignal>(OnEnemyKilled);
        }

        public static void DestroyCurrentLevel()
        {
            var currentLevel = FindObjectOfType<Level>().gameObject;
            Destroy(currentLevel);
        }

        private void ProcessFinalLevel()
        {
            var sun = FindObjectOfType<Light>();
            
            if (_isFinalLevel)
            {
                sun.intensity = 1;
                SetSkyTint(Color.cyan);
                _audio.PlayMusic(MusicType.FinalTheme);
            }
            else
            {
                sun.intensity = 0;
                SetSkyTint(Color.red);
                _audio.PlayMusic(MusicType.MainTheme);
            }
        }

        private void SetSkyTint(Color color)
        {
            if (RenderSettings.skybox.HasProperty("_Tint"))
                RenderSettings.skybox.SetColor("_Tint", color);
            else if (RenderSettings.skybox.HasProperty("_SkyTint"))
                RenderSettings.skybox.SetColor("_SkyTint", color);
        }
    }
}