using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;

public class ConfigLinkViewerWindow : EditorWindow
{
    private string selectedTableName;
    private Vector2 scrollPos;
    private Dictionary<string, bool> expandedRelations = new Dictionary<string, bool>();
    private Vector2 relationScrollPos;
    private string searchFilter = "";
    private bool showOnlyExisting = true;

    [MenuItem("Tools/配置表联动查看器")]
    public static void ShowWindow()
    {
        GetWindow<ConfigLinkViewerWindow>("配置表联动");
    }

    private void OnGUI()
    {
        DrawHeader();
        EditorGUILayout.Space();
        DrawTableSelector();
        EditorGUILayout.Space();

        if (!string.IsNullOrEmpty(selectedTableName))
        {
            DrawTableInfo();
        }
    }

    private void DrawHeader()
    {
        EditorGUILayout.BeginVertical("box");
        EditorGUILayout.LabelField("配置表联动关系查看器", new GUIStyle(EditorStyles.boldLabel) { fontSize = 14 });
        EditorGUILayout.LabelField("选择配置表查看其与其他表的关联关系", EditorStyles.miniLabel);
        EditorGUILayout.EndVertical();
    }

    private void DrawTableSelector()
    {
        EditorGUILayout.BeginVertical("box");

        EditorGUILayout.LabelField("选择配置表:", EditorStyles.boldLabel);

        EditorGUILayout.BeginHorizontal();
        searchFilter = EditorGUILayout.TextField("搜索:", searchFilter, EditorStyles.toolbarSearchField);
        showOnlyExisting = EditorGUILayout.ToggleLeft("只显示当前项目存在的表", showOnlyExisting, GUILayout.Width(160));
        EditorGUILayout.EndHorizontal();

        var allTables = showOnlyExisting ? ConfigLinkDatabase.GetExistingTables() : ConfigLinkDatabase.GetAllTableInfo();
        var filteredTables = string.IsNullOrEmpty(searchFilter)
            ? allTables
            : allTables.Where(t => t.displayName.Contains(searchFilter) ||
                                   t.tableName.Contains(searchFilter) ||
                                   t.description.Contains(searchFilter)).ToList();

        var displayNames = filteredTables.Select(x => 
        {
            string existMark = showOnlyExisting ? "" : (x.isExistInProject ? "[存在]" : "[缺失]");
            return $"{x.displayName} ({x.tableName}) {existMark}";
        }).ToArray();
        
        var tableKeys = filteredTables.Select(x => x.tableName).ToArray();

        int selectedIndex = selectedTableName != null ? System.Array.IndexOf(tableKeys, selectedTableName) : 0;
        selectedIndex = Mathf.Clamp(selectedIndex, 0, Mathf.Max(0, displayNames.Length - 1));

        EditorGUILayout.Space();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.BeginVertical(GUILayout.Width(200));
        EditorGUILayout.LabelField($"配置表列表 ({filteredTables.Count}):", EditorStyles.miniBoldLabel);
        relationScrollPos = EditorGUILayout.BeginScrollView(relationScrollPos, GUILayout.Height(300));

        for (int i = 0; i < displayNames.Length; i++)
        {
            bool isSelected = tableKeys[i] == selectedTableName;
            GUIStyle buttonStyle = isSelected ? "Button" : "Label";

            if (GUILayout.Button(displayNames[i], buttonStyle))
            {
                selectedTableName = tableKeys[i];
                expandedRelations.Clear();
            }
        }

        EditorGUILayout.EndScrollView();
        EditorGUILayout.EndVertical();

        EditorGUILayout.BeginVertical("box", GUILayout.MinWidth(400));
        DrawCurrentTableInfo();
        EditorGUILayout.EndVertical();

        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();
    }

    private void DrawCurrentTableInfo()
    {
        if (string.IsNullOrEmpty(selectedTableName))
        {
            EditorGUILayout.LabelField("请从左侧选择一个配置表", EditorStyles.centeredGreyMiniLabel);
            return;
        }

        var tableInfo = ConfigLinkDatabase.GetTableInfo(selectedTableName);
        if (tableInfo == null)
        {
            EditorGUILayout.LabelField("未找到该表的配置信息", EditorStyles.helpBox);
            return;
        }

        EditorGUILayout.LabelField($"当前表: {tableInfo.displayName}", EditorStyles.boldLabel);
        EditorGUILayout.LabelField($"表名: {tableInfo.tableName}", EditorStyles.miniLabel);
        EditorGUILayout.LabelField($"描述: {tableInfo.description}", EditorStyles.miniLabel);
        EditorGUILayout.LabelField($"状态: {(tableInfo.isExistInProject ? "存在于当前项目" : "当前项目不存在")}", 
            tableInfo.isExistInProject ? EditorStyles.miniLabel : EditorStyles.helpBox);

        EditorGUILayout.Space();

        if (tableInfo.relations.Count == 0)
        {
            EditorGUILayout.LabelField("该表暂无联动关系", EditorStyles.miniLabel);
        }
        else
        {
            EditorGUILayout.LabelField($"联动关系 ({tableInfo.relations.Count}):", EditorStyles.boldLabel);
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Height(250));

            foreach (var relation in tableInfo.relations)
            {
                DrawRelation(relation);
            }

            EditorGUILayout.EndScrollView();
        }
    }

    private void DrawRelation(FieldRelation relation)
    {
        string key = $"{selectedTableName}_{relation.fieldName}_{relation.targetTable}";
        if (!expandedRelations.ContainsKey(key))
        {
            expandedRelations[key] = false;
        }

        bool targetExist = ConfigLinkDatabase.IsTableExist(relation.targetTable);
        string existMark = targetExist ? "" : "[目标表缺失]";

        EditorGUILayout.BeginVertical("frameBox");
        expandedRelations[key] = EditorGUILayout.Foldout(expandedRelations[key],
            $"{relation.fieldName} → {relation.targetTable}.{relation.targetField} {existMark}",
            true);

        if (expandedRelations[key])
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.Space();
            EditorGUILayout.BeginVertical("helpBox");

            EditorGUILayout.LabelField($"目标表: {relation.targetTable} {(targetExist ? "" : "(当前项目不存在)")}", 
                targetExist ? EditorStyles.miniLabel : EditorStyles.helpBox);
            EditorGUILayout.LabelField($"目标字段: {relation.targetField}", EditorStyles.miniLabel);

            if (!string.IsNullOrEmpty(relation.relationFormat))
            {
                EditorGUILayout.LabelField($"格式: {relation.relationFormat}", EditorStyles.miniLabel);
            }

            EditorGUILayout.LabelField($"说明: {relation.description}", EditorStyles.miniLabel);

            if (targetExist && GUILayout.Button($"查看 {relation.targetTable} 表", EditorStyles.miniButton, GUILayout.Width(120)))
            {
                selectedTableName = relation.targetTable;
                expandedRelations.Clear();
            }

            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
        }

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

    private void DrawTableInfo()
    {
        var tableInfo = ConfigLinkDatabase.GetTableInfo(selectedTableName);
        if (tableInfo == null) return;

        EditorGUILayout.BeginVertical("box");

        EditorGUILayout.LabelField($"当前表: {tableInfo.displayName} ({tableInfo.tableName})", EditorStyles.boldLabel);
        EditorGUILayout.LabelField($"描述: {tableInfo.description}", EditorStyles.miniLabel);

        EditorGUILayout.Space();

        if (tableInfo.relations.Count == 0)
        {
            EditorGUILayout.LabelField("暂无联动关系", EditorStyles.miniLabel);
        }
        else
        {
            EditorGUILayout.LabelField("联动关系:", EditorStyles.boldLabel);

            scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Height(300));

            foreach (var relation in tableInfo.relations)
            {
                DrawRelationItem(relation);
            }

            EditorGUILayout.EndScrollView();
        }

        EditorGUILayout.EndVertical();
    }

    private void DrawRelationItem(FieldRelation relation)
    {
        string key = $"{selectedTableName}_{relation.fieldName}";
        if (!expandedRelations.ContainsKey(key))
        {
            expandedRelations[key] = true;
        }

        bool targetExist = ConfigLinkDatabase.IsTableExist(relation.targetTable);

        expandedRelations[key] = EditorGUILayout.Foldout(expandedRelations[key],
            $"字段: {relation.fieldName} → {relation.targetTable} {(targetExist ? "" : "(缺失)")}");

        if (expandedRelations[key])
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.Space();

            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField($"目标字段: {relation.targetField}", EditorStyles.miniLabel);

            if (!string.IsNullOrEmpty(relation.relationFormat))
            {
                EditorGUILayout.LabelField($"数据格式: {relation.relationFormat}", EditorStyles.miniLabel);
            }

            EditorGUILayout.LabelField($"说明: {relation.description}", EditorStyles.miniLabel);

            if (targetExist && GUILayout.Button($"跳转到 {relation.targetTable}", EditorStyles.miniButton))
            {
                selectedTableName = relation.targetTable;
                Repaint();
                return;
            }

            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
        }
    }
}
