using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class EnemySpawner : MonoBehaviour
{

    [SerializeField] private GameObject[] enemyPrefabs;
    [SerializeField] private Transform enemyParent;
    [SerializeField] private bool isFloorLevel;
    
    private Transform playerTransform;
    private AudioSource audioSource;
    
    private PlayerCombat _playerCombat;
    
    private bool _isFirstEnemySpawned;
    
    void Start()
    {
        StartCoroutine(SpawnFirstEnemy());
        
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
        audioSource = GetComponent<AudioSource>();
        _playerCombat = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerCombat>();
    }

    
    void Update()
    {
        if(_isFirstEnemySpawned) CheckEnemyCount();
    }

    private void CheckEnemyCount()
    {
        int childCount = enemyParent.transform.childCount;
        if (childCount < 3 && _playerCombat.enemiesToDefeat > childCount)
        {
            SpawnEnemy();
        }
    }

    public void SpawnEnemy()
    {
        float distance = 0;
        Vector3 spawnPosition = Vector3.zero;
        do
        {
            int random_x = Random.Range(-18, 18);
            int random_y = Random.Range(-3, -8);
            if (isFloorLevel)
            {
                random_x = Random.Range(-60, 60);
                random_y = Random.Range(0, 4);
            }
            spawnPosition = new Vector3(random_x, random_y, transform.position.z);
            distance = (playerTransform.position - spawnPosition).magnitude;
            //Debug.Log("Distance to player: " + distance);
        } while (distance <= 12f);

        int randomIdx = Random.Range(0, enemyPrefabs.Length);
        GameObject enemy = Instantiate(enemyPrefabs[randomIdx], spawnPosition, Quaternion.identity, enemyParent);
        if (isFloorLevel)
        {
            enemy.transform.localScale = Vector3.one * 2.0f;
            enemy.GetComponent<EnemyEntity>().Config.attackRadius *= 2;
        }
        SpawnVFX(spawnPosition);
        audioSource.Play();
    }

    private void SpawnVFX(Vector2 spawnPosition)
    {
        if (HitEffectManager.Instance == null) return;
        HitEffectManager.Instance.Spawn(HitEffectType.SpawnEffect, spawnPosition, Vector2.right);
    }
    private IEnumerator SpawnFirstEnemy()
    {
        yield return new WaitForSeconds(3.0f);
        SpawnEnemy();
        _isFirstEnemySpawned = true;
    }
}
