using UnityEditor;
using UnityEngine;
using AlicizaX.UI;
using AlicizaX.UI.Runtime;

[CustomEditor(typeof(UXController))]
public class UXControllerEditor : Editor
{
    private SerializedProperty _controllersProp;

    private void OnEnable()
    {
        _controllersProp = serializedObject.FindProperty("_controllers");
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        EditorGUILayout.LabelField("UX Controller", EditorStyles.boldLabel);
        EditorGUILayout.Space();
        EditorGUI.BeginDisabledGroup(true);

        for (int i = 0; i < _controllersProp.arraySize; i++)
        {
            var el = _controllersProp.GetArrayElementAtIndex(i);
            var nameProp = el.FindPropertyRelative("Name");
            var lengthProp = el.FindPropertyRelative("Length");

            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField($"[{i}]", GUILayout.Width(30));
            nameProp.stringValue = EditorGUILayout.TextField(nameProp.stringValue);
            if (GUILayout.Button("Remove", GUILayout.Width(70)))
            {
                _controllersProp.DeleteArrayElementAtIndex(i);
                break;
            }

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Length", GUILayout.Width(50));
            lengthProp.intValue = Mathf.Max(1, EditorGUILayout.IntField(lengthProp.intValue));
            EditorGUILayout.EndHorizontal();


            var ux = target as UXController;
            if (ux != null && ux.Controllers != null && i < ux.Controllers.Count)
            {
                EditorGUILayout.LabelField("CurrentIndex", ux.Controllers[i].CurrentIndex.ToString());
            }

            EditorGUILayout.EndVertical();
            EditorGUILayout.Space();
        }

        var controller = target as UXController;
        using (new EditorGUILayout.VerticalScope("Box"))
        {
            foreach (var recorder in controller.Recorders)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField($"ID:{recorder.ID}", EditorStyles.helpBox);
                EditorGUILayout.ObjectField(recorder, typeof(UXControllerStateRecorder), true);
                EditorGUILayout.EndHorizontal();
            }
        }

        EditorGUI.EndDisabledGroup();
        serializedObject.ApplyModifiedProperties();
    }
}
