#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 void OnEnable()
        {
            _item = (ItemData_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Preview", EditorStyles.boldLabel);

            if (_item.icon != null)
            {
                Rect rect = GUILayoutUtility.GetRect(64, 64);
                EditorGUI.DrawPreviewTexture(rect, _item.icon.texture);
            }

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Computed Values", EditorStyles.boldLabel);

            var rules = FindRules();
            if (rules != null)
            {
                WeightTier tier = rules.GetTier(_item.weight);
                float speedMult = rules.GetSpeedMultiplier(tier);
                EditorGUILayout.LabelField($"Weight Tier (alone): {tier}");
                EditorGUILayout.LabelField($"Speed Multiplier (alone): {speedMult:P0}");
                EditorGUILayout.LabelField($"Value/Weight Ratio: {(_item.weight > 0 ? _item.lootValue / _item.weight : 0):F2}");
            }

            EditorGUILayout.Space();
            if (GUILayout.Button("Generate ID from Name"))
            {
                Undo.RecordObject(_item, "Generate Item ID");
                _item.itemId = _item.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_item);
            }

            DrawValidation();
        }

        private void DrawValidation()
        {
            EditorGUILayout.Space();
            if (string.IsNullOrEmpty(_item.itemId))
                EditorGUILayout.HelpBox("Item ID is empty.", MessageType.Error);
            if (_item.worldPrefab == null)
                EditorGUILayout.HelpBox("No world prefab assigned.", MessageType.Warning);
            if (_item.lootValue <= 0)
                EditorGUILayout.HelpBox("Loot value is 0 or negative.", MessageType.Warning);
            if (_item.weight <= 0)
                EditorGUILayout.HelpBox("Weight is 0 or negative.", MessageType.Warning);
        }

        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
