using UnityEngine;

namespace MaskShop
{
    /// <summary>
    /// Manages the workbench zone where masks are assembled
    /// </summary>
    public class WorkbenchZone : MonoBehaviour
    {
        [Header("Zone Settings")]
        [SerializeField] private Transform maskPlacementPoint;

        [Header("Camera Settings")]
        // [SerializeField] private CinemachineVirtualCamera workbenchCamera;
        // Commented - You'll configure this manually

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

        // State
        private GameObject currentMask;
        private MaskAssembly currentMaskAssembly;
        private bool isPlayerInZone = false;
        private PlayerInventory playerInventory;

        // Events
        public static event System.Action<MaskAssembly> OnMaskPlaced;

        private void Start()
        {
            if (maskPlacementPoint == null)
            {
                Debug.LogWarning("WorkbenchZone: Mask placement point not assigned! Creating one...");
                GameObject placementPoint = new GameObject("MaskPlacementPoint");
                placementPoint.transform.SetParent(transform);
                placementPoint.transform.localPosition = Vector3.zero;
                maskPlacementPoint = placementPoint.transform;
            }
        }

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

                // If player is carrying a mold, automatically place it
                if (playerInventory != null && playerInventory.IsCarrying())
                {
                    PlaceMoldOnWorkbench();
                }

                if (showDebugInfo)
                {
                    Debug.Log("WorkbenchZone: Player entered workbench zone");
                }
            }
        }

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

                if (showDebugInfo)
                {
                    Debug.Log("WorkbenchZone: Player exited workbench zone");
                }
            }
        }

        /// <summary>
        /// Places the carried mold on the workbench
        /// </summary>
        private void PlaceMoldOnWorkbench()
        {
            if (currentMask != null)
            {
                if (showDebugInfo) Debug.Log("WorkbenchZone: Workbench already has a mask!");
                return;
            }

            if (playerInventory == null || !playerInventory.IsCarrying()) return;

            // Get mold from player
            GameObject moldObject = playerInventory.DropMoldAtWorkbench();
            MaskMold moldData = playerInventory.GetCurrentMoldData();

            // --- CORRECCIÓN AQUÍ ---
            moldObject.transform.SetParent(maskPlacementPoint);

            // Al poner la posición local en cero, se mueve exactamente donde está el punto
            moldObject.transform.localPosition = Vector3.zero;

            // CAMBIO: En lugar de Quaternion.identity, usamos identity para que coincida 
            // perfectamente con la rotación del padre (maskPlacementPoint)
            moldObject.transform.localRotation = Quaternion.identity;

            // NOTA: Si pones localRotation = Quaternion.identity DESPUÉS de hacer SetParent,
            // el objeto se alineará EXACTAMENTE con la rotación de maskPlacementPoint.
            // -----------------------

            currentMask = moldObject;

            currentMaskAssembly = currentMask.GetComponent<MaskAssembly>();
            if (currentMaskAssembly == null)
            {
                currentMaskAssembly = currentMask.AddComponent<MaskAssembly>();
            }

            currentMaskAssembly.Initialize(moldData);
            OnMaskPlaced?.Invoke(currentMaskAssembly);

            if (showDebugInfo)
            {
                Debug.Log($"WorkbenchZone: Placed {moldData.MoldName} on workbench with rotation {maskPlacementPoint.rotation.eulerAngles}");
            }
        }
        /// <summary>
        /// Removes the current mask from workbench (after delivery)
        /// </summary>
        public void ClearWorkbench()
        {
            if (currentMask != null)
            {
                Destroy(currentMask);
                currentMask = null;
                currentMaskAssembly = null;

                if (showDebugInfo)
                {
                    Debug.Log("WorkbenchZone: Workbench cleared");
                }
            }
        }

        /// <summary>
        /// Gets the current mask assembly
        /// </summary>
        public MaskAssembly GetCurrentMaskAssembly() => currentMaskAssembly;

        public bool HasMask() => currentMask != null;
        public bool IsPlayerInZone() => isPlayerInZone;
    }
}