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

namespace IStalk.Editor.Inspectors
{
    [CustomEditor(typeof(EyeType_SO))]
    public class EyeTypeEditor : UnityEditor.Editor
    {
        private EyeType_SO _eyeType;
        private bool _showAbilityPreview = true;
        private bool _showStatPreview = true;

        private void OnEnable()
        {
            _eyeType = (EyeType_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space(15);

            _showAbilityPreview = EditorGUILayout.Foldout(_showAbilityPreview, "Ability Summary", true);
            if (_showAbilityPreview)
            {
                EditorGUI.indentLevel++;
                DrawAbilityMatrix();
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space(10);
            _showStatPreview = EditorGUILayout.Foldout(_showStatPreview, "Effective Stats Preview", true);
            if (_showStatPreview)
            {
                EditorGUI.indentLevel++;
                DrawStatPreview();
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space(10);
            DrawQuickActions();
            DrawValidation();
        }

        private void DrawAbilityMatrix()
        {
            EditorGUILayout.LabelField("Enabled Abilities:", EditorStyles.boldLabel);

            bool hasLaser = _eyeType.HasAbility(EyeAbility.Laser);
            bool hasScan = _eyeType.HasAbility(EyeAbility.Scan);
            bool hasTraps = _eyeType.HasAbility(EyeAbility.Traps);
            bool hasIncarnation = _eyeType.HasAbility(EyeAbility.Incarnation);

            DrawAbilityRow("Laser", hasLaser, "Fire damaging beam at runners");
            DrawAbilityRow("Scan", hasScan, "Reveal all runners briefly");
            DrawAbilityRow("Traps", hasTraps, "Place traps on the map");
            DrawAbilityRow("Incarnation", hasIncarnation, "Possess and move props");
            DrawAbilityRow("Eyelids", _eyeType.hasEyelids, "Close eyes to dodge flash (skill timing)");

            int abilityCount = (hasLaser ? 1 : 0) + (hasScan ? 1 : 0) + (hasTraps ? 1 : 0) + (hasIncarnation ? 1 : 0);
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField($"Total: {abilityCount}/4 abilities active");
        }

        private void DrawAbilityRow(string name, bool enabled, string tooltip)
        {
            string icon = enabled ? "✓" : "✗";
            Color color = enabled ? new Color(0.2f, 0.8f, 0.2f) : new Color(0.5f, 0.5f, 0.5f);
            var style = new GUIStyle(EditorStyles.label) { richText = true };
            string colorHex = ColorUtility.ToHtmlStringRGB(color);
            EditorGUILayout.LabelField(new GUIContent($"  <color=#{colorHex}>{icon}</color> {name}", tooltip), style);
        }

        private void DrawStatPreview()
        {
            var rules = FindRules();
            if (rules == null)
            {
                EditorGUILayout.HelpBox("GlobalRules_SO not found. Create one to see effective stats.", MessageType.Info);
                return;
            }

            EditorGUILayout.LabelField("Laser", EditorStyles.boldLabel);
            if (_eyeType.HasAbility(EyeAbility.Laser))
            {
                float cd = rules.laserCooldown * _eyeType.laserCooldownMultiplier;
                float rad = rules.laserRadius * _eyeType.laserRadiusMultiplier;
                EditorGUILayout.LabelField($"  Cooldown: {cd:F1}s (base {rules.laserCooldown:F1} x {_eyeType.laserCooldownMultiplier:F2})");
                EditorGUILayout.LabelField($"  Radius: {rad:F2}m (base {rules.laserRadius:F2} x {_eyeType.laserRadiusMultiplier:F2})");
                EditorGUILayout.LabelField($"  DPS potential: {1f / cd:F2} shots/sec");
            }
            else
            {
                EditorGUILayout.LabelField("  (Disabled for this type)");
            }

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Scan", EditorStyles.boldLabel);
            if (_eyeType.HasAbility(EyeAbility.Scan))
            {
                float cd = (rules.laserCooldown * 3f) * _eyeType.scanCooldownMultiplier;
                float rad = 30f * _eyeType.scanRadiusMultiplier;
                EditorGUILayout.LabelField($"  Cooldown: {cd:F1}s (x{_eyeType.scanCooldownMultiplier:F2})");
                EditorGUILayout.LabelField($"  Radius: {rad:F1}m (x{_eyeType.scanRadiusMultiplier:F2})");
            }
            else
            {
                EditorGUILayout.LabelField("  (Disabled for this type)");
            }

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Traps", EditorStyles.boldLabel);
            if (_eyeType.HasAbility(EyeAbility.Traps))
            {
                EditorGUILayout.LabelField($"  Cost multiplier: {_eyeType.trapCostMultiplier:F2}x (lower = cheaper)");
                EditorGUILayout.LabelField($"  Max active bonus: +{_eyeType.trapMaxActiveBonus}");
            }
            else
            {
                EditorGUILayout.LabelField("  (Disabled for this type)");
            }

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Dread", EditorStyles.boldLabel);
            if (_eyeType.dreadStartOverride >= 0)
                EditorGUILayout.LabelField($"  Starting Dread: {_eyeType.dreadStartOverride:F0} (override)");
            else
                EditorGUILayout.LabelField($"  Starting Dread: {rules.dreadStartingAmount:F0} (default)");

            if (_eyeType.dreadRegenOverride >= 0)
                EditorGUILayout.LabelField($"  Regen rate: {_eyeType.dreadRegenOverride:F1}/s (override)");
            else
                EditorGUILayout.LabelField($"  Regen rate: {rules.dreadBaseRegenRate:F1}/s (default)");
        }

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

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Generate ID from Name"))
            {
                Undo.RecordObject(_eyeType, "Generate Eye Type ID");
                _eyeType.typeId = _eyeType.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_eyeType);
            }

            if (GUILayout.Button("Preset: Watcher"))
            {
                ApplyPreset(new[] { EyeAbility.Scan, EyeAbility.Incarnation }, false,
                    1f, 1f, 0.6f, 1.3f, 1f, 0);
            }

            if (GUILayout.Button("Preset: Predator"))
            {
                ApplyPreset(new[] { EyeAbility.Laser, EyeAbility.Incarnation }, true,
                    0.5f, 1.4f, 1f, 1f, 1f, 0);
            }

            if (GUILayout.Button("Preset: Trapper"))
            {
                ApplyPreset(new[] { EyeAbility.Traps, EyeAbility.Scan, EyeAbility.Incarnation }, false,
                    1f, 1f, 1f, 1f, 0.6f, 3);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void ApplyPreset(EyeAbility[] abilities, bool eyelids,
            float laserCd, float laserRad, float scanCd, float scanRad, float trapCost, int trapBonus)
        {
            Undo.RecordObject(_eyeType, "Apply Eye Type Preset");
            _eyeType.enabledAbilities = abilities;
            _eyeType.hasEyelids = eyelids;
            _eyeType.laserCooldownMultiplier = laserCd;
            _eyeType.laserRadiusMultiplier = laserRad;
            _eyeType.scanCooldownMultiplier = scanCd;
            _eyeType.scanRadiusMultiplier = scanRad;
            _eyeType.trapCostMultiplier = trapCost;
            _eyeType.trapMaxActiveBonus = trapBonus;
            EditorUtility.SetDirty(_eyeType);
        }

        private void DrawValidation()
        {
            EditorGUILayout.Space(10);
            if (string.IsNullOrEmpty(_eyeType.typeId))
                EditorGUILayout.HelpBox("Type ID is empty. Click 'Generate ID from Name'.", MessageType.Error);
            if (string.IsNullOrEmpty(_eyeType.displayName))
                EditorGUILayout.HelpBox("Display Name is empty.", MessageType.Warning);
            if (_eyeType.enabledAbilities == null || _eyeType.enabledAbilities.Length == 0)
                EditorGUILayout.HelpBox("No abilities enabled! This eye type will have no actions.", MessageType.Error);
            if (_eyeType.icon == null)
                EditorGUILayout.HelpBox("No icon assigned (optional for greybox).", 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
