using System;
using System.Timers;
using Cybe;
using Sources.Gui;
using UnityEngine;
using Zenject;

namespace Sources
{
    public class Portal : MonoBehaviour
    {
        [SerializeField] private Level _level;

        [Inject] private GuiController _guiController;
        [Inject] private DiContainer _container;
        [Inject] private AudioManager _audioManager;
        [Inject] private Player _player;

        private int _enteredPlayerParts;
        private bool _teleporting;
        private float _progress;

        private void OnTriggerEnter(Collider other)
        {
            Debug.Log($"{other.name} entered the portal!");

            var enteredPlayer = other.GetComponentInParent<Player>();
            if (!enteredPlayer)
                return;

            _enteredPlayerParts++;
        }

        private void OnTriggerExit(Collider other)
        {
            Debug.Log($"{other.name} exited the portal!");

            var enteredPlayer = other.GetComponentInParent<Player>();
            if (!enteredPlayer)
                return;

            _enteredPlayerParts--;
        }

        private void Update()
        {
            if (_enteredPlayerParts > 0 && _player.IsAlive)
            {
                _teleporting = true;
                _progress += Time.deltaTime * 0.2f;
                _guiController.SetTeleportingProgress(_progress);

                if (_progress >= 1)
                {
                    Teleport();
                    _enteredPlayerParts = 0;
                }
            }
            else if (_teleporting)
            {
                _progress = 0;
                _guiController.SetTeleportingProgress(_progress);

                _teleporting = false;
            }
        }

        private void Teleport()
        {
            _audioManager.PlayFx(SoundType.Portal);

            _guiController.FadeInAndOut(onFaded: () =>
            {
                Level.DestroyCurrentLevel();

                var level = _container.InstantiatePrefabForComponent<Level>(_level);
                _player.transform.position = level.SpawnPoint;
            });
        }
    }
}