#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using IStalk.Data;

namespace IStalk.Editor.Inspectors
{
    [CustomEditor(typeof(ItemData_SO))]
    public class ItemDataEditor : UnityEditor.Editor
    {
        private ItemData_SO _item;
        private bool _showDesignerPanel = true;

        private void OnEnable()
        {
            _item = (ItemData_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

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

            DrawIconPreview();
            DrawBalanceInfo();
            DrawComparison();
            DrawQuickActions();
            DrawValidation();
        }

        private void DrawIconPreview()
        {
            if (_item.icon != null)
            {
                EditorGUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                Rect rect = GUILayoutUtility.GetRect(80, 80);
                EditorGUI.DrawPreviewTexture(rect, _item.icon.texture);
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.Space(5);
            }
        }

        private void DrawBalanceInfo()
        {
            var rules = FindRules();
            if (rules == null)
            {
                EditorGUILayout.HelpBox("Create a GlobalRules_SO to see balance info.", MessageType.Info);
                return;
            }

            EditorGUILayout.LabelField("Impact Analysis", EditorStyles.boldLabel);

            WeightTier tier = rules.GetTier(_item.weight);
            float speedMult = rules.GetSpeedMultiplier(tier);
            float ratio = _item.weight > 0 ? (float)_item.lootValue / _item.weight : 0;

            EditorGUILayout.LabelField($"  Weight Tier (alone): {tier}");
            EditorGUILayout.LabelField($"  Speed when carrying: {rules.baseRunSpeed * speedMult:F1} m/s ({speedMult:P0})");
            EditorGUILayout.LabelField($"  Value/Weight Ratio: {ratio:F2}");

            EditorGUILayout.Space(3);
            EditorGUILayout.LabelField("Economy Context", EditorStyles.boldLabel);
            float pctOfThreshold = (float)_item.lootValue / rules.extractionThreshold * 100f;
            EditorGUILayout.LabelField($"  Extraction contribution: {pctOfThreshold:F0}% of threshold ({_item.lootValue}/{rules.extractionThreshold})");
            float channelTime = rules.GetChannelTime(_item.weight);
            EditorGUILayout.LabelField($"  Channel time carrying this: {channelTime:F1}s");

            Color barColor = ratio > 2f ? Color.green : ratio > 1f ? Color.yellow : Color.red;
            string riskLabel = ratio > 2f ? "High reward" : ratio > 1f ? "Balanced" : "Risky (heavy for value)";
            var style = new GUIStyle(EditorStyles.label) { richText = true };
            string hex = ColorUtility.ToHtmlStringRGB(barColor);
            EditorGUILayout.LabelField($"  Risk/Reward: <color=#{hex}>{riskLabel}</color>", style);
        }

        private void DrawComparison()
        {
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Loot Pool Context", EditorStyles.boldLabel);

            var allItems = Resources.LoadAll<ItemData_SO>("Items/Loot");
            if (allItems.Length <= 1)
            {
                EditorGUILayout.LabelField("  (Create more items to see comparisons)");
                return;
            }

            float avgWeight = 0, avgValue = 0;
            foreach (var item in allItems) { avgWeight += item.weight; avgValue += item.lootValue; }
            avgWeight /= allItems.Length;
            avgValue /= allItems.Length;

            EditorGUILayout.LabelField($"  This item: {_item.weight:F1}kg / {_item.lootValue} value");
            EditorGUILayout.LabelField($"  Pool average: {avgWeight:F1}kg / {avgValue:F1} value ({allItems.Length} items total)");

            if (_item.weight > avgWeight * 1.5f)
                EditorGUILayout.LabelField("  → Heavier than average (consider higher value)");
            if (_item.lootValue > avgValue * 2f)
                EditorGUILayout.LabelField("  → Very high value (rare spawn weight recommended)");
        }

        private void DrawQuickActions()
        {
            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Quick Actions", EditorStyles.boldLabel);

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Generate ID"))
            {
                Undo.RecordObject(_item, "Generate Item ID");
                _item.itemId = _item.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_item);
            }
            if (GUILayout.Button("Preset: Common"))
            {
                Undo.RecordObject(_item, "Preset Common");
                _item.weight = 1; _item.lootValue = 1; _item.rarity = Rarity.Common;
                EditorUtility.SetDirty(_item);
            }
            if (GUILayout.Button("Preset: Rare"))
            {
                Undo.RecordObject(_item, "Preset Rare");
                _item.weight = 4; _item.lootValue = 7; _item.rarity = Rarity.Rare;
                EditorUtility.SetDirty(_item);
            }
            if (GUILayout.Button("Preset: Legendary"))
            {
                Undo.RecordObject(_item, "Preset Legendary");
                _item.weight = 7; _item.lootValue = 12; _item.rarity = Rarity.Legendary;
                EditorUtility.SetDirty(_item);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawValidation()
        {
            EditorGUILayout.Space(10);
            bool hasIssues = false;

            if (string.IsNullOrEmpty(_item.itemId))
            { EditorGUILayout.HelpBox("Item ID is empty. Click 'Generate ID'.", MessageType.Error); hasIssues = true; }
            if (_item.worldPrefab == null)
            { EditorGUILayout.HelpBox("No world prefab assigned (needed for spawning in-world).", MessageType.Warning); hasIssues = true; }
            if (_item.lootValue <= 0)
            { EditorGUILayout.HelpBox("Loot value is 0 — item won't contribute to extraction.", MessageType.Warning); hasIssues = true; }
            if (_item.weight <= 0)
            { EditorGUILayout.HelpBox("Weight is 0 — item won't slow runner at all.", MessageType.Warning); hasIssues = true; }

            if (!hasIssues)
                EditorGUILayout.HelpBox("All checks pass. Item is ready.", MessageType.Info);
        }

        private GlobalRules_SO FindRules()
        {
            if (GlobalRules_SO.Instance != null) return GlobalRules_SO.Instance;
            string[] guids = AssetDatabase.FindAssets("t:GlobalRules_SO");
            if (guids.Length == 0) return null;
            return AssetDatabase.LoadAssetAtPath<GlobalRules_SO>(AssetDatabase.GUIDToAssetPath(guids[0]));
        }
    }
}
#endif
