using AlicizaX.Editor;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace UnityEngine.UI
{
    [CustomEditor(typeof(UXGroup))]
    public class UXGroupInspector : GameFrameworkInspector
    {
        private SerializedProperty m_Buttons;
        private UXGroup _target;
        private ReorderableList _reorderableList;

        private void OnEnable()
        {
            _target = (UXGroup)target;
            m_Buttons = serializedObject.FindProperty("m_Buttons");

            _reorderableList = new ReorderableList(serializedObject, m_Buttons, true, true, true, true)
            {
                drawHeaderCallback = DrawHeader,
                drawElementCallback = DrawElement,
                onAddCallback = OnAddList,
                onRemoveCallback = OnRemoveList,
                onChangedCallback = OnChanged,
            };
        }

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

            bool isPlaying = Application.isPlaying || EditorApplication.isPlaying;

            _reorderableList.draggable = !isPlaying;
            _reorderableList.displayAdd = !isPlaying;
            _reorderableList.displayRemove = !isPlaying;

            bool prevEnabled = GUI.enabled;
            if (isPlaying) GUI.enabled = false;

            _reorderableList.DoLayoutList();

            GUI.enabled = prevEnabled;

            serializedObject.ApplyModifiedProperties();
        }

        private void DrawHeader(Rect rect)
        {
            EditorGUI.LabelField(rect, "Toggles", EditorStyles.boldLabel);
        }

        // 记录旧的引用用于侦测变化
        private UXButton previousRef;

        private void DrawElement(Rect rect, int index, bool isActive, bool isFocused)
        {
            SerializedProperty element = m_Buttons.GetArrayElementAtIndex(index);

            rect.y += 2;
            Rect fieldRect = new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight);

            UXButton oldButton = element.objectReferenceValue as UXButton;

            string label = $"[{index}] {(oldButton != null ? oldButton.name : "Null")}";

            EditorGUI.BeginChangeCheck();

            var newRef = EditorGUI.ObjectField(fieldRect, label, oldButton, typeof(UXButton), true) as UXButton;

            if (EditorGUI.EndChangeCheck())
            {
                // 先处理 Remove（旧值存在且不同）
                if (oldButton != null && oldButton != newRef)
                {
                    OnRemove(oldButton);
                }

                // 再处理 Add（新值非空）
                if (newRef != null && oldButton != newRef)
                {
                    OnAdd(newRef);
                }

                // 最后把引用写回去
                element.objectReferenceValue = newRef;
            }
        }

        private void OnAddList(ReorderableList list)
        {
            int newIndex = m_Buttons.arraySize;
            m_Buttons.arraySize++;
            serializedObject.ApplyModifiedProperties();

            var newElem = m_Buttons.GetArrayElementAtIndex(newIndex);
            newElem.objectReferenceValue = null;
            serializedObject.ApplyModifiedProperties();
        }

        private void OnRemoveList(ReorderableList list)
        {
            if (list.index < 0 || list.index >= m_Buttons.arraySize)
                return;

            var oldButton = m_Buttons.GetArrayElementAtIndex(list.index).objectReferenceValue as UXButton;
            if (oldButton)
            {
                OnRemove(oldButton);
            }

            m_Buttons.DeleteArrayElementAtIndex(list.index);
            serializedObject.ApplyModifiedProperties();
        }

        private void OnChanged(ReorderableList list)
        {
            serializedObject.ApplyModifiedProperties();
        }

        // ========================
        // 你的新增方法：自动调用
        // ========================

        private void OnAdd(UXButton button)
        {
            SerializedObject so = new SerializedObject(button);
            var groupProp = so.FindProperty("m_UXGroup");
            groupProp.objectReferenceValue = target;

            UXGroup group = (UXGroup)target;
            group.RegisterButton(button);

            so.ApplyModifiedProperties();
        }

        private void OnRemove(UXButton button)
        {
            SerializedObject so = new SerializedObject(button);
            var groupProp = so.FindProperty("m_UXGroup");

            UXGroup group = groupProp.objectReferenceValue as UXGroup;
            if (group != null)
                group.UnregisterButton(button);

            groupProp.objectReferenceValue = null;

            so.ApplyModifiedProperties();
        }
    }
}
