#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Linq;
using IStalk.Data;
using IStalk.EditorTools.MapGen;

namespace IStalk.Editor.MapGen
{
    [CustomEditor(typeof(RoomNode_SO))]
    public class RoomNodeEditor : UnityEditor.Editor
    {
        private RoomNode_SO _room;
        private bool _showValidation = true;
        private bool _showDesignerPanel = true;

        private void OnEnable()
        {
            _room = (RoomNode_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space(15);
            _showDesignerPanel = EditorGUILayout.Foldout(_showDesignerPanel, "Designer Panel", true);
            if (!_showDesignerPanel) return;

            DrawRoomSummary();
            DrawMapGenContext();
            DrawRoomTools();
            DrawValidationResults();
        }

        private void DrawRoomSummary()
        {
            EditorGUILayout.LabelField("Room Summary", EditorStyles.boldLabel);

            EditorGUILayout.LabelField($"  Category: {_room.category}");
            EditorGUILayout.LabelField($"  Grid Size: {_room.gridSize} ({_room.gridSize.x * _room.gridSize.z} cells)");
            EditorGUILayout.LabelField($"  Connections: {_room.openConnections.Count} ({string.Join(", ", _room.openConnections)})");

            EditorGUILayout.Space(3);
            EditorGUILayout.LabelField("Content Slots", EditorStyles.boldLabel);
            EditorGUILayout.LabelField($"  Loot: {_room.lootSpawnSlots}");
            EditorGUILayout.LabelField($"  Incarnation Props: {_room.incarnationPropSlots}");
            EditorGUILayout.LabelField($"  Runner Spawn: {(_room.isValidRunnerSpawn ? "Yes" : "No")}");
            EditorGUILayout.LabelField($"  Altar Location: {(_room.isValidAltarLocation ? "Yes" : "No")}");
            EditorGUILayout.LabelField($"  Shrine: {(_room.canContainShrine ? "Yes" : "No")}");
        }

        private void DrawMapGenContext()
        {
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Map Generation Context", EditorStyles.boldLabel);

            var allRooms = Resources.LoadAll<RoomNode_SO>("Items/Rooms");
            if (allRooms.Length == 0) return;

            int sameCategory = allRooms.Count(r => r.category == _room.category);
            float totalWeight = allRooms.Where(r => r.category == _room.category).Sum(r => r.spawnWeight);
            float myChance = totalWeight > 0 ? (_room.spawnWeight / totalWeight) * 100f : 0;

            EditorGUILayout.LabelField($"  Rooms in '{_room.category}' pool: {sameCategory}");
            EditorGUILayout.LabelField($"  Spawn weight: {_room.spawnWeight} ({myChance:F1}% chance when picking from pool)");
            EditorGUILayout.LabelField($"  Max per map: {(_room.maxPerMap <= 0 ? "Unlimited" : _room.maxPerMap.ToString())}");

            if (_room.openConnections.Count <= 1)
                EditorGUILayout.HelpBox("Only 1 connection → dead-end room. Good for special rooms, limits map flow.", MessageType.Info);
            else if (_room.openConnections.Count >= 4)
                EditorGUILayout.HelpBox("4+ connections → hub room. Creates branching paths, great for large rooms.", MessageType.Info);
        }

        private void DrawRoomTools()
        {
            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Room Tools", EditorStyles.boldLabel);

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Auto-Populate from Prefab"))
                AutoPopulate();
            if (GUILayout.Button("Generate ID"))
            {
                Undo.RecordObject(_room, "Generate Room ID");
                _room.roomId = _room.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_room);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Select Prefab"))
            {
                if (_room.roomPrefab != null)
                    Selection.activeObject = _room.roomPrefab;
            }
            if (GUILayout.Button("Open Prefab"))
            {
                if (_room.roomPrefab != null)
                    AssetDatabase.OpenAsset(_room.roomPrefab);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void AutoPopulate()
        {
            if (_room.roomPrefab == null)
            {
                EditorUtility.DisplayDialog("Error", "Assign a room prefab first.", "OK");
                return;
            }

            Undo.RecordObject(_room, "Auto-Populate Room Node");

            var prefab = _room.roomPrefab;

            var connectors = prefab.GetComponentsInChildren<ConnectorMarker>(true);
            _room.openConnections.Clear();
            foreach (var c in connectors)
            {
                if (!_room.openConnections.Contains(c.connectionDirection))
                    _room.openConnections.Add(c.connectionDirection);
            }

            var bounds = prefab.GetComponentInChildren<RoomBounds>(true);
            if (bounds != null)
                _room.gridSize = bounds.gridSize;

            var slots = prefab.GetComponentsInChildren<SpawnSlot>(true);
            _room.lootSpawnSlots = slots.Count(s => s.slotType == SpawnSlotType.LootItem);
            _room.incarnationPropSlots = slots.Count(s => s.slotType == SpawnSlotType.PropIncarnation);
            _room.isValidRunnerSpawn = slots.Any(s => s.slotType == SpawnSlotType.RunnerSpawn);
            _room.isValidAltarLocation = slots.Any(s => s.slotType == SpawnSlotType.AltarLocation);
            _room.canContainShrine = slots.Any(s => s.slotType == SpawnSlotType.Shrine);

            if (string.IsNullOrEmpty(_room.roomId))
                _room.roomId = _room.name.Replace(" ", "_").ToLower();

            EditorUtility.SetDirty(_room);
            Debug.Log($"[RoomNodeEditor] Auto-populated: {connectors.Length} connectors, {slots.Length} slots, grid {_room.gridSize}");
        }

        private void DrawValidationResults()
        {
            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Validation", EditorStyles.boldLabel);

            bool valid = true;

            if (string.IsNullOrEmpty(_room.roomId))
            {
                EditorGUILayout.HelpBox("Room ID is empty. Click 'Generate ID'.", MessageType.Error);
                valid = false;
            }

            if (_room.roomPrefab == null)
            {
                EditorGUILayout.HelpBox("No prefab assigned. Drag a room prefab here.", MessageType.Error);
                valid = false;
            }
            else
            {
                var connectors = _room.roomPrefab.GetComponentsInChildren<ConnectorMarker>(true);
                if (connectors.Length == 0)
                    EditorGUILayout.HelpBox("Prefab has no ConnectorMarker components — room can't connect to anything.", MessageType.Error);

                var bounds = _room.roomPrefab.GetComponentInChildren<RoomBounds>(true);
                if (bounds == null)
                    EditorGUILayout.HelpBox("Prefab has no RoomBounds — MapGenerator can't size it.", MessageType.Warning);
            }

            if (_room.openConnections.Count == 0)
            {
                EditorGUILayout.HelpBox("No connections defined — click 'Auto-Populate' to read from prefab.", MessageType.Warning);
            }

            if (_room.gridSize.x <= 0 || _room.gridSize.y <= 0 || _room.gridSize.z <= 0)
            {
                EditorGUILayout.HelpBox("Grid size has zero or negative dimension.", MessageType.Error);
                valid = false;
            }

            if (_room.spawnWeight <= 0)
            {
                EditorGUILayout.HelpBox("Spawn weight is 0 — room will NEVER appear in generated maps.", MessageType.Warning);
            }

            if (_room.lootSpawnSlots == 0 && _room.category != RoomCategory.Corridor)
            {
                EditorGUILayout.HelpBox("No loot slots — runners can't find items here.", MessageType.Info);
            }

            if (valid && _room.roomPrefab != null)
                EditorGUILayout.HelpBox("Room passes all checks. Ready for map generation.", MessageType.Info);
        }
    }
}
#endif
