using RebootKit.Engine.Services.Console;
using SzafaKitEditor.VisualElements;
using UnityEditor;
using UnityEngine;

namespace SzafaKitEditor.PropertyDrawers {
    [CustomPropertyDrawer(typeof(CVar))]
    public class CVarPropertyDrawer : PropertyDrawer {
        private bool _expand;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
            SerializedProperty nameProperty = property.FindPropertyRelative("Name");
            SerializedProperty descriptionProperty = property.FindPropertyRelative("Description");
            SerializedProperty defaultValueProperty = property.FindPropertyRelative("DefaultValue");
            SerializedProperty defaultValueKindProperty = defaultValueProperty.FindPropertyRelative("Kind");
            SerializedProperty defaultValueNumberProperty = defaultValueProperty.FindPropertyRelative("NumberValue");
            SerializedProperty defaultValueStringProperty = defaultValueProperty.FindPropertyRelative("StringValue");

            EditorGUILayout.BeginHorizontal();
            
            GUILayout.Label(label, EditorStyles.miniBoldLabel);

            nameProperty.stringValue = EditorGUILayout.TextField(nameProperty.stringValue);

            bool isNumber = defaultValueKindProperty.enumValueIndex == (int) CVarValueKind.Number;
            string kindLabel = isNumber ? "N" : "S";

            if (isNumber) {
                GUI.color = Color.cyan;
            } else {
                GUI.color = Color.green;
            }
            
            if (GUILayout.Button(kindLabel, GUILayout.Width(32))) {
                defaultValueKindProperty.enumValueIndex = isNumber ? (int) CVarValueKind.String : (int) CVarValueKind.Number;
            }

            GUI.color = Color.white;

            if (isNumber) {
                defaultValueNumberProperty.doubleValue = EditorGUILayout.DoubleField(defaultValueNumberProperty.doubleValue);
            } else {
                defaultValueStringProperty.stringValue = EditorGUILayout.TextField(defaultValueStringProperty.stringValue);
            }

            if (GUILayout.Button(_expand ? "H" : "S", GUILayout.MaxWidth(24))) {
                _expand = !_expand;
            }

            EditorGUILayout.EndHorizontal();

            if (_expand) {
                EditorGUILayout.PropertyField(nameProperty, new GUIContent("Name"));
                EditorGUILayout.PropertyField(descriptionProperty, new GUIContent("Description"));
                EditorGUILayout.PropertyField(defaultValueKindProperty, new GUIContent("Value Kind"));
                EditorGUILayout.PropertyField(defaultValueNumberProperty, new GUIContent("Number"));
                EditorGUILayout.PropertyField(defaultValueStringProperty, new GUIContent("String"));
            }
        }
    }
}