using System;
using KBCore.Refs;
using UnityEngine;

namespace Infrastructure.Unity
{
    [RequireComponent(typeof(AudioSource))]
    public class SoundManager : MonoBehaviour
    {
        [Header("Music")]
        [SerializeField] private AudioClip bgMusicClip;
        
        [Header("Sound Effects")]
        [SerializeField] private AudioClip startClip;
        [SerializeField] private AudioClip scoreClip;
        [SerializeField] private AudioClip gameOverClip;
        [SerializeField] private AudioClip tileWarningClip;
        [SerializeField] private AudioClip tileBreakClip;
        [SerializeField] private AudioClip npcSpawnClip;
        
        [SerializeField] private AudioSource musicSource;
        [SerializeField] private AudioSource sfxSource;

        private void Awake()
        {
            musicSource.loop = true;
            musicSource.playOnAwake = false;
        }

        public void PlayMusic()
        {
            if (!bgMusicClip) return;
            
            musicSource.clip = bgMusicClip;
            musicSource.Play();
        }

        public void StopMusic()
        {
            musicSource.Stop();
        }
        
        public void PlayGameStart() => PlaySfx(startClip);
        public void PlayScore() => PlaySfx(scoreClip);
        public void PlayGameOver() => PlaySfx(gameOverClip);
        
        public void PlayNpcSpawn() => PlaySfx(npcSpawnClip);

        public void PlayTileBreak(Vector3 position)
        {
            if (!tileBreakClip) return;
            
            AudioSource.PlayClipAtPoint(tileBreakClip, position, 1f);
        }
        
        public void PlayTileWarning(Vector3 position) 
        {
            if (!tileWarningClip) return;
            
            AudioSource.PlayClipAtPoint(tileWarningClip, position, 0.5f);
        }
        
        private void PlaySfx(AudioClip clip)
        {
            if (!clip) return;
            
            sfxSource.PlayOneShot(clip);
        }
        
        public void SetPaused(bool isPaused)
        {
            if (isPaused)
            {
                musicSource.Pause();
            }
            else
            {
                musicSource.UnPause();
            }
            
            AudioListener.pause = isPaused;
        }
    }
}