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

namespace MaskShop
{
    /// <summary>
    /// Manages the decoration/materials selection zone
    /// </summary>
    public class DecorationSelector : MonoBehaviour
    {
        [Header("Zone Settings")]
        [SerializeField] private List<DecorationItem> availableDecorations = new List<DecorationItem>();
        [SerializeField] private Transform decorationsDisplayParent;
        [SerializeField] private float decorationSpacing = 1.5f;

        [Header("Camera Settings")]
        [SerializeField] private CinemachineCamera decorationCamera;
        [Header("References")]
        [SerializeField] private QTESystem qteSystem;
        [SerializeField] private WorkbenchZone workbenchZone;

        [Header("Interaction")]
        [SerializeField] private LayerMask decorationLayer;

        [Header("Grid Settings")]
        [SerializeField] private int gridColumns = 4; // Cuántos elementos por fila
        [SerializeField] private float verticalSpacing = 1.2f; // Espacio entre filas

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

        // State
        private bool isPlayerInZone = false;
        private Dictionary<GameObject, DecorationItem> decorationInstanceMap = new Dictionary<GameObject, DecorationItem>();
        private List<GameObject> spawnedDecorationInstances = new List<GameObject>();
        private MaskAssembly currentMask;
        private bool processingQTE = false;

        private void Start()
        {
            SpawnDecorationDisplays();
        }

        private void OnEnable()
        {
            QTESystem.OnQTECompleted += OnQTECompleted;
            WorkbenchZone.OnMaskPlaced += OnMaskPlaced;
        }

        private void OnDisable()
        {
            QTESystem.OnQTECompleted -= OnQTECompleted;
            WorkbenchZone.OnMaskPlaced -= OnMaskPlaced;
        }

        /// <summary>
        /// Spawns all available decorations for display
        /// </summary>
        private void SpawnDecorationDisplays()
        {
            if (decorationsDisplayParent == null) return;

            int displayIndex = 0;

            for (int i = 0; i < availableDecorations.Count; i++)
            {
                DecorationItem decorationData = availableDecorations[i];
                if (!decorationData.IsUnlocked) continue;

                // --- CÁLCULO DE CUADRÍCULA ---
                int column = displayIndex % gridColumns;
                int row = displayIndex / gridColumns;

                // Calculamos el desplazamiento usando los ejes locales del padre
                Vector3 offset = (decorationsDisplayParent.right * column * decorationSpacing) +
                                 (decorationsDisplayParent.up * -row * verticalSpacing); // -row para que baje

                Vector3 position = decorationsDisplayParent.position + offset;
                Quaternion rotation = decorationsDisplayParent.rotation;
                // -----------------------------

                GameObject displayInstance;

                if (decorationData.Type == DecorationType.PaletteDecoration)
                {
                    displayInstance = CreatePaletteDisplay(decorationData, position, rotation);
                }
                else
                {
                    if (decorationData.DecorationPrefab == null) continue;
                    displayInstance = Instantiate(decorationData.DecorationPrefab, position, rotation, decorationsDisplayParent);
                    displayInstance.name = $"{decorationData.DecorationName}_Display";
                }

                EnsureInteractionComponents(displayInstance);
                decorationInstanceMap[displayInstance] = decorationData;
                spawnedDecorationInstances.Add(displayInstance);

                displayIndex++;
            }
        }
        /// <summary>
        /// Creates a visual display for palette decorations
        /// </summary>
        // Actualizamos este método para que reciba posición y rotación ya calculadas
        private GameObject CreatePaletteDisplay(DecorationItem paletteData, Vector3 position, Quaternion rotation)
        {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = position;
            cube.transform.rotation = rotation; // Respeta la rotación del padre
            cube.transform.SetParent(decorationsDisplayParent);
            cube.transform.localScale = Vector3.one * 0.5f;
            cube.name = $"{paletteData.DecorationName}_Display";

            if (paletteData.PaletteMaterial != null)
            {
                cube.GetComponent<Renderer>().material = paletteData.PaletteMaterial;
            }

            return cube;
        }

        /// <summary>
        /// Ensures decoration has necessary components for interaction
        /// </summary>
        private void EnsureInteractionComponents(GameObject decorationInstance)
        {
            // Add collider if missing
            if (decorationInstance.GetComponent<Collider>() == null)
            {
                BoxCollider collider = decorationInstance.AddComponent<BoxCollider>();
            }

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

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

                if (decorationCamera != null) decorationCamera.Priority = 20;

                if (showDebugInfo)
                {
                    Debug.Log("DecorationSelector: Player entered decoration zone");
                }
            }
        }

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


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

                if (showDebugInfo)
                {
                    Debug.Log("DecorationSelector: Player exited decoration zone");
                }
            }
        }

        /// <summary>
        /// Called when mask is placed on workbench
        /// </summary>
        private void OnMaskPlaced(MaskAssembly maskAssembly)
        {
            currentMask = maskAssembly;

            if (showDebugInfo)
            {
                Debug.Log("DecorationSelector: Mask placed on workbench, ready for decoration");
            }
        }

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

            if (currentMask == null)
            {
                if (showDebugInfo)
                {
                    Debug.Log("DecorationSelector: No mask on workbench!");
                }
                return;
            }

            if (processingQTE)
            {
                if (showDebugInfo)
                {
                    Debug.Log("DecorationSelector: Already processing a QTE!");
                }
                return;
            }

            // Get decoration data
            if (!decorationInstanceMap.TryGetValue(decorationInstance, out DecorationItem decorationData))
            {
                Debug.LogWarning("DecorationSelector: Clicked decoration not in map!");
                return;
            }

            // Start QTE for this decoration
            StartDecorationQTE(decorationData);
        }

        /// <summary>
        /// Starts a QTE for decoration placement
        /// </summary>
        private void StartDecorationQTE(DecorationItem decorationData)
        {
            if (qteSystem == null)
            {
                Debug.LogError("DecorationSelector: QTE System not assigned!");
                return;
            }

            processingQTE = true;

            // Store decoration data for when QTE completes
            StartCoroutine(ProcessDecorationWithQTE(decorationData));
        }

        /// <summary>
        /// Processes decoration application with QTE
        /// </summary>
        private IEnumerator ProcessDecorationWithQTE(DecorationItem decorationData)
        {
            // Start QTE
            qteSystem.StartQTE(decorationData.QteType, decorationData.QteDifficulty);

            if (showDebugInfo)
            {
                Debug.Log($"DecorationSelector: Started QTE for {decorationData.DecorationName}");
            }

            // Wait for QTE to complete (handled by event)
            yield return new WaitUntil(() => !qteSystem.IsQTEActive());

            // Apply decoration with result
            QTEResult result = qteSystem.GetCurrentResult();

            if (decorationData.Type == DecorationType.PaletteDecoration)
            {
                currentMask.ApplyPalette(decorationData, result);
            }
            else
            {
                currentMask.ApplyDecoration(decorationData, result);
            }

            processingQTE = false;

            if (showDebugInfo)
            {
                Debug.Log($"DecorationSelector: Applied {decorationData.DecorationName} with {result} result");
            }
        }

        /// <summary>
        /// Called when QTE is completed
        /// </summary>
        private void OnQTECompleted(QTEResult result)
        {
            if (showDebugInfo)
            {
                Debug.Log($"DecorationSelector: QTE completed with {result}");
            }
        }

        /// <summary>
        /// Refreshes decoration display when new items are unlocked
        /// </summary>
        public void RefreshDecorationDisplay()
        {
            // Clear existing displays
            foreach (GameObject instance in spawnedDecorationInstances)
            {
                Destroy(instance);
            }

            spawnedDecorationInstances.Clear();
            decorationInstanceMap.Clear();

            // Respawn
            SpawnDecorationDisplays();
        }

        public bool IsPlayerInZone() => isPlayerInZone;
    }

    /// <summary>
    /// Component attached to decoration instances to handle mouse events
    /// </summary>
    public class DecorationInteractable : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
    {
        private DecorationSelector selector;
        private Renderer decorationRenderer;
        private Material originalMaterial;

        public void Initialize(DecorationSelector decorationSelector)
        {
            selector = decorationSelector;
            decorationRenderer = GetComponentInChildren<Renderer>();

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

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

        public void OnPointerEnter(PointerEventData eventData)
        {
            // Visual feedback on hover
            if (decorationRenderer != null && selector.IsPlayerInZone())
            {
                // TODO: Add highlight effect
            }
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            // Remove visual feedback
            if (decorationRenderer != null && originalMaterial != null)
            {
                // TODO: Remove highlight effect
            }
        }
    }
}