using UnityEngine;

namespace MaskShop
{
    /// <summary>
    /// Manages the spawning of ogre customers
    /// </summary>
    public class OgreSpawner : MonoBehaviour
    {
        [Header("Spawn Settings")]
        [SerializeField] private GameObject ogrePrefab;
        [SerializeField] private Transform spawnPosition;
        [SerializeField] private Transform shopPosition;
        [SerializeField] private RequestGenerator requestGenerator;

        [Header("Debug")]
        [SerializeField] private bool showDebugInfo = true;

        // Estado interno
        private GameObject currentOgre;
        private bool canSpawn = false;

        private void OnEnable()
        {
            // Suscribirse al evento de finalización del ogro
            OgreEvents.OnOgreFinished += OnOgreFinished;
        }

        private void OnDisable()
        {
            // Desuscribirse del evento
            OgreEvents.OnOgreFinished -= OnOgreFinished;
        }

        private void Start()
        {
            ValidateReferences();
        }

        private void Update()
        {
            // Verificar si el juego ha comenzado y podemos spawnear
            CheckGameStarted();

            // Si podemos spawnear y no hay ogro activo, spawnear uno
            if (canSpawn && currentOgre == null)
            {
                SpawnOgre();
            }
        }

        /// <summary>
        /// Verifica si el GameManager indica que el juego ha comenzado
        /// </summary>
        private void CheckGameStarted()
        {
            // Verificar si existe GameManager y si el juego ha comenzado
            if (GameManager.Instance != null && GameManager.Instance.gameStarted)
            {
                canSpawn = true;
            }
            else
            {
                canSpawn = false;
            }
        }

        /// <summary>
        /// Instancia un nuevo ogro en la escena
        /// </summary>
        private void SpawnOgre()
        {
            if (ogrePrefab == null)
            {
                Debug.LogError("OgreSpawner: Ogre prefab is not assigned!");
                return;
            }

            if (spawnPosition == null)
            {
                Debug.LogError("OgreSpawner: Spawn position is not assigned!");
                return;
            }

            // Instanciar el ogro
            currentOgre = Instantiate(ogrePrefab, spawnPosition.position, spawnPosition.rotation);

            // Configurar el OgreBehavior
            OgreBehavior ogreBehavior = currentOgre.GetComponent<OgreBehavior>();
            if (ogreBehavior == null)
            {
                Debug.LogError("OgreSpawner: Spawned prefab does not have OgreBehavior component!");
                Destroy(currentOgre);
                currentOgre = null;
                return;
            }

            // Asignar referencias necesarias mediante reflection o un método de setup
            SetupOgreBehavior(ogreBehavior);

            if (showDebugInfo)
            {
                Debug.Log($"OgreSpawner: New ogre spawned at {spawnPosition.position}");
            }
        }

        /// <summary>
        /// Configura el OgreBehavior con las referencias necesarias
        /// </summary>
        private void SetupOgreBehavior(OgreBehavior ogreBehavior)
        {
            // Usar reflection para asignar valores privados o crear un método público en OgreBehavior
            // Por ahora, asumimos que OgreBehavior tiene estos campos públicos o serializados en el prefab

            // Si prefieres, puedes crear un método público Setup() en OgreBehavior:
            // ogreBehavior.Setup(shopPosition, requestGenerator);

            if (showDebugInfo)
            {
                Debug.Log("OgreSpawner: OgreBehavior configured successfully");
            }
        }

        /// <summary>
        /// Callback cuando un ogro termina su rutina
        /// </summary>
        private void OnOgreFinished()
        {
            if (showDebugInfo)
            {
                Debug.Log("OgreSpawner: Ogre finished routine, ready to spawn next one");
            }

            currentOgre = null;
        }

        /// <summary>
        /// Valida que todas las referencias necesarias estén asignadas
        /// </summary>
        private void ValidateReferences()
        {
            bool isValid = true;

            if (ogrePrefab == null)
            {
                Debug.LogError("OgreSpawner: Ogre Prefab is not assigned!");
                isValid = false;
            }

            if (spawnPosition == null)
            {
                Debug.LogError("OgreSpawner: Spawn Position is not assigned!");
                isValid = false;
            }

            if (shopPosition == null)
            {
                Debug.LogError("OgreSpawner: Shop Position is not assigned!");
                isValid = false;
            }

            if (requestGenerator == null)
            {
                Debug.LogError("OgreSpawner: Request Generator is not assigned!");
                isValid = false;
            }

            if (isValid && showDebugInfo)
            {
                Debug.Log("OgreSpawner: All references validated successfully");
            }
        }

        /// <summary>
        /// Fuerza el spawn de un ogro (útil para testing)
        /// </summary>
        [ContextMenu("Force Spawn Ogre")]
        public void ForceSpawnOgre()
        {
            if (currentOgre != null)
            {
                Debug.LogWarning("OgreSpawner: There is already an active ogre!");
                return;
            }

            SpawnOgre();
        }

        /// <summary>
        /// Elimina el ogro actual (útil para testing)
        /// </summary>
        [ContextMenu("Remove Current Ogre")]
        public void RemoveCurrentOgre()
        {
            if (currentOgre != null)
            {
                Destroy(currentOgre);
                currentOgre = null;

                if (showDebugInfo)
                {
                    Debug.Log("OgreSpawner: Current ogre removed");
                }
            }
        }

        // Getters públicos
        public bool HasActiveOgre() => currentOgre != null;
        public GameObject GetCurrentOgre() => currentOgre;

#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            if (spawnPosition != null)
            {
                // Dibujar posición de spawn
                Gizmos.color = Color.blue;
                Gizmos.DrawWireSphere(spawnPosition.position, 0.5f);
                Gizmos.DrawLine(spawnPosition.position, spawnPosition.position + spawnPosition.forward * 2f);
            }

            if (shopPosition != null)
            {
                // Dibujar posición de la tienda
                Gizmos.color = Color.green;
                Gizmos.DrawWireSphere(shopPosition.position, 0.5f);

                // Dibujar línea desde spawn hasta tienda
                if (spawnPosition != null)
                {
                    Gizmos.color = Color.yellow;
                    Gizmos.DrawLine(spawnPosition.position, shopPosition.position);
                }
            }
        }
#endif
    }
}