using System.Collections.Generic;
using Unity.Cinemachine;
using UnityEngine;
using UnityEngine.EventSystems;

namespace MaskShop
{
    /// <summary>
    /// Manages the mold selection zone and interaction
    /// </summary>
    public class MaskMoldSelector : MonoBehaviour
    {
        [Header("Zone Settings")]
        [SerializeField] private List<MaskMold> availableMolds = new List<MaskMold>();
        [SerializeField] private Transform moldsDisplayParent;
        [SerializeField] private float moldSpacing = 2f;

        [Header("Camera Settings")]
        [SerializeField] private CinemachineCamera selectionCamera;


        [Header("Interaction")]
        [SerializeField] private LayerMask moldLayer;
        [SerializeField] private float selectionCooldown = 0.5f;

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

        // State
        private bool isPlayerInZone = false;
        private PlayerInventory playerInventory;
        private Dictionary<GameObject, MaskMold> moldInstanceMap = new Dictionary<GameObject, MaskMold>();
        private float lastSelectionTime;
        private List<GameObject> spawnedMoldInstances = new List<GameObject>();

        private void Start()
        {
            SpawnMoldDisplays();
        }

        /// <summary>
        /// Spawns all available molds for display
        /// </summary>
        private void SpawnMoldDisplays()
        {
            if (moldsDisplayParent == null) return;

            for (int i = 0; i < availableMolds.Count; i++)
            {
                MaskMold moldData = availableMolds[i];
                if (!moldData.IsUnlocked || moldData.MoldPrefab == null) continue;

                // --- CONFIGURACIÓN DE BARAJA ---
                // 'right' controla qué tan "desplazados" están hacia un lado.
                // 'forward' controla qué tan "adelante" se pone cada uno respecto al anterior.

                float lateralOverlap = moldSpacing * 0.2f; // Mucho más cerca (20% del spacing original)
                float depthOffset = 0.5f; // Grosor para evitar que se atraviesen (ajusta según el grosor del disco)

                Vector3 position = moldsDisplayParent.position
                                   + (moldsDisplayParent.right * i * lateralOverlap)
                                   + (moldsDisplayParent.forward * i * -depthOffset); // El negativo lo trae "hacia la cámara"

                Quaternion rotation = moldsDisplayParent.rotation;

                GameObject moldInstance = Instantiate(moldData.MoldPrefab, position, rotation, moldsDisplayParent);

                // Si el molde es gigante como en la imagen, podemos normalizar la escala aquí
                // moldInstance.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); 

                moldInstance.name = $"{moldData.MoldName}_Display";
                EnsureInteractionComponents(moldInstance);

                moldInstanceMap[moldInstance] = moldData;
                spawnedMoldInstances.Add(moldInstance);
            }
        }
        /// <summary>
        /// Ensures the mold has necessary components for mouse interaction
        /// </summary>
        private void EnsureInteractionComponents(GameObject moldInstance)
        {
            // Add collider if missing
            if (moldInstance.GetComponent<Collider>() == null)
            {
                BoxCollider collider = moldInstance.AddComponent<BoxCollider>();
                if (showDebugInfo)
                {
                    Debug.Log($"MaskMoldSelector: Added BoxCollider to {moldInstance.name}");
                }
            }

            // Add MoldInteractable component
            MoldInteractable interactable = moldInstance.GetComponent<MoldInteractable>();
            if (interactable == null)
            {
                interactable = moldInstance.AddComponent<MoldInteractable>();
                interactable.Initialize(this);
            }
        }

        /// <summary>
        /// Trigger enter - player enters mold selection zone
        /// </summary>
        private void OnTriggerEnter(Collider other)
        {
            if (other.CompareTag("Player"))
            {
                isPlayerInZone = true;
                playerInventory = other.GetComponent<PlayerInventory>();

                if (selectionCamera != null) selectionCamera.Priority = 20;
                if (showDebugInfo)
                {
                    Debug.Log("MaskMoldSelector: Player entered mold selection zone");
                }
            }
        }

        /// <summary>
        /// Trigger exit - player leaves mold selection zone
        /// </summary>
        private void OnTriggerExit(Collider other)
        {
            if (other.CompareTag("Player"))
            {
                isPlayerInZone = false;
                playerInventory = null;

                if (selectionCamera != null) selectionCamera.Priority = 0;

                if (showDebugInfo)
                {
                    Debug.Log("MaskMoldSelector: Player exited mold selection zone");
                }
            }
        }

        /// <summary>
        /// Called when a mold is clicked
        /// </summary>
        public void OnMoldClicked(GameObject moldInstance)
        {
            if (!isPlayerInZone)
            {
                if (showDebugInfo)
                {
                    Debug.Log("MaskMoldSelector: Player not in zone, ignoring click");
                }
                return;
            }

            if (playerInventory == null)
            {
                Debug.LogWarning("MaskMoldSelector: No PlayerInventory found!");
                return;
            }

            if (playerInventory.IsCarrying())
            {
                if (showDebugInfo)
                {
                    Debug.Log("MaskMoldSelector: Player already carrying a mold");
                }
                return;
            }

            // Cooldown check
            if (Time.time - lastSelectionTime < selectionCooldown)
            {
                return;
            }

            lastSelectionTime = Time.time;

            // Get mold data
            if (!moldInstanceMap.TryGetValue(moldInstance, out MaskMold moldData))
            {
                Debug.LogWarning("MaskMoldSelector: Clicked mold not in map!");
                return;
            }

            // Create a new instance for the player to carry
            GameObject carriedMold = Instantiate(moldData.MoldPrefab);
            carriedMold.name = moldData.MoldName;

            // Give to player
            playerInventory.PickupMold(carriedMold, moldData);

            if (showDebugInfo)
            {
                Debug.Log($"MaskMoldSelector: Player selected {moldData.MoldName}");
            }
        }

        /// <summary>
        /// Refreshes the display when new molds are unlocked
        /// </summary>
        public void RefreshMoldDisplay()
        {
            // Clear existing displays
            foreach (GameObject instance in spawnedMoldInstances)
            {
                Destroy(instance);
            }

            spawnedMoldInstances.Clear();
            moldInstanceMap.Clear();

            // Respawn
            SpawnMoldDisplays();
        }

        public bool IsPlayerInZone() => isPlayerInZone;
    }

    /// <summary>
    /// Component attached to mold instances to handle mouse events
    /// </summary>
    public class MoldInteractable : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
    {
        private MaskMoldSelector selector;
        private Material originalMaterial;
        private Renderer moldRenderer;

        public void Initialize(MaskMoldSelector moldSelector)
        {
            selector = moldSelector;
            moldRenderer = GetComponentInChildren<Renderer>();

            if (moldRenderer != null)
            {
                originalMaterial = moldRenderer.material;
            }
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            selector?.OnMoldClicked(gameObject);
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            // Visual feedback on hover
            if (moldRenderer != null && selector.IsPlayerInZone())
            {
                // TODO: Add highlight effect
                // moldRenderer.material.SetColor("_EmissionColor", Color.white * 0.5f);
            }
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            // Remove visual feedback
            if (moldRenderer != null && originalMaterial != null)
            {
                // TODO: Remove highlight effect
                // moldRenderer.material.SetColor("_EmissionColor", Color.black);
            }
        }
    }
}