using UnityEngine;
using UnityEditor;
using DefaultNamespace.ProcessMode;
using System.Collections.Generic;
using UnityEngine.UIElements;
using System.Linq;

public class ProcessScoreWindow : EditorWindow
{
    private Vector2 scrollPosition;
    private ProcessManager processManager;
    private bool[] stepFoldouts;
    private GUIStyle headerStyle;
    private GUIStyle subHeaderStyle;
    private GUIStyle scoreStyle;
    private GUIStyle warningStyle;

    [MenuItem("Window/Process Score Viewer")]
    public static void ShowWindow()
    {
        var window = GetWindow<ProcessScoreWindow>("流程得分查看器");
        window.minSize = new Vector2(400, 300);
    }

    private void OnEnable()
    {
        // 初始化样式
        InitializeStyles();
        
        // 获取 ProcessManager 实例
        processManager = MotionFramework.MotionEngine.GetModule<ProcessManager>();
        if (processManager != null && processManager.CurrentProcessCollection != null)
        {
            stepFoldouts = new bool[processManager.CurrentProcessCollection.Steps.Count];
        }
    }

    private void InitializeStyles()
    {
        headerStyle = new GUIStyle(EditorStyles.boldLabel)
        {
            fontSize = 14,
            margin = new RectOffset(4, 4, 8, 8)
        };

        subHeaderStyle = new GUIStyle(EditorStyles.boldLabel)
        {
            fontSize = 12,
            margin = new RectOffset(4, 4, 4, 4)
        };

        scoreStyle = new GUIStyle(EditorStyles.label)
        {
            fontSize = 11,
            normal = { textColor = Color.black }
        };

        warningStyle = new GUIStyle(EditorStyles.label)
        {
            fontSize = 11,
            normal = { textColor = Color.red }
        };
    }

    private void OnGUI()
    {
        if (processManager == null)
        {
            EditorGUILayout.HelpBox("未找到 ProcessManager 实例", MessageType.Warning);
            return;
        }

        if (processManager.CurrentProcessCollection == null)
        {
            EditorGUILayout.HelpBox("当前没有活动的流程集合", MessageType.Info);
            return;
        }

        scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

        var steps = processManager.CurrentProcessCollection.Steps;
        
        // 显示总体信息
        EditorGUILayout.LabelField("流程总览", headerStyle);
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        EditorGUILayout.LabelField($"当前模式: {processManager._currentMode}");
        EditorGUILayout.LabelField($"总步骤数: {steps.Count}");
        EditorGUILayout.LabelField($"已完成步骤: {steps.Count(s => s.IsCompleted)}/{steps.Count}");
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space(10);

        // 显示每个步骤的详细信息
        for (int i = 0; i < steps.Count; i++)
        {
            var step = steps[i];
            
            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            
            // 步骤标题栏
            EditorGUILayout.BeginHorizontal();
            stepFoldouts[i] = EditorGUILayout.Foldout(stepFoldouts[i], 
                $"步骤 {i + 1}: {step.StepDescription}", true);
            
            // 显示步骤状态
            string status = step.IsCompleted ? "✓ 已完成" : "✗ 未完成";
            GUIStyle statusStyle = step.IsCompleted ? scoreStyle : warningStyle;
            EditorGUILayout.LabelField(status, statusStyle, GUILayout.Width(60));
            
            EditorGUILayout.EndHorizontal();

            if (stepFoldouts[i])
            {
                EditorGUI.indentLevel++;
                
                // 显示步骤下的所有动作
                for (int j = 0; j < step.Actions.Count; j++)
                {
                    var action = step.Actions[j];
                    
                    EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                    EditorGUILayout.LabelField($"动作 {j + 1}: {action.Title}", subHeaderStyle);
                    EditorGUILayout.LabelField($"描述: {action.Description}");
                    EditorGUILayout.LabelField($"满分: {action.Score}");

                    // 显示目标物体
                    EditorGUILayout.LabelField("目标物体:", subHeaderStyle);
                    foreach (var target in action.TargetObjects)
                    {
                        EditorGUILayout.LabelField($"- {target.ObjectName} ({target.Type})");
                    }

                    // 显示错误点击信息
                    if (processManager._incorrectClicksPerStep.TryGetValue(i, out var incorrectClicks))
                    {
                        // 只显示当前动作的错误点击
                        var currentActionErrors = incorrectClicks
                            .Where(error => action.TargetObjects.Any(target => target.ObjectName == error))
                            .ToList();

                        if (currentActionErrors.Count > 0)
                        {
                            EditorGUILayout.LabelField("错误点击:", warningStyle);
                            EditorGUILayout.LabelField($"次数: {currentActionErrors.Count}");
                            EditorGUILayout.LabelField($"物体: {string.Join(", ", currentActionErrors)}");
                            
                            float scorePerObject = action.Score / action.TargetObjects.Count;
                            float deductedScore = action.Score - scorePerObject * currentActionErrors.Count;
                            deductedScore = Mathf.Max(0, deductedScore);
                            
                            EditorGUILayout.LabelField($"实际得分: {deductedScore:F2}/{action.Score}");
                        }
                        else
                        {
                            EditorGUILayout.LabelField($"实际得分: {action.Score}/{action.Score} (完美完成)");
                        }
                    }
                    else
                    {
                        // 添加调试信息
                        EditorGUILayout.LabelField($"当前索引: {action.CurrentObjectIndex}");
                        EditorGUILayout.LabelField($"目标数量: {action.TargetObjects.Count}");
                        
                        if (action.CurrentObjectIndex >= action.TargetObjects.Count)
                        {
                            EditorGUILayout.LabelField($"实际得分: {action.Score}/{action.Score} (完美完成)");
                        }
                        else
                        {
                            EditorGUILayout.LabelField($"实际得分: 0/{action.Score} (未完成)", warningStyle);
                        }
                    }
                    
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.Space(5);
                }
                
                EditorGUI.indentLevel--;
            }
            
            EditorGUILayout.EndVertical();
            EditorGUILayout.Space(5);
        }

        EditorGUILayout.EndScrollView();

        // 添加刷新按钮
        EditorGUILayout.Space(10);
        if (GUILayout.Button("刷新数据"))
        {
            Repaint();
        }
    }
}