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

namespace AvatarRefinery.ErrorGuide
{
    /// <summary>Console のエラーを、日本語（または英語）の説明つきで仕分けて見せる画面。</summary>
    public class ConsoleErrorWindow : EditorWindow
    {
        class Group
        {
            public ConsoleErrorRule Rule;        // null は「未登録」
            public List<ConsoleItem> Items = new List<ConsoleItem>();
            public int Total => Items.Sum(i => i.Count);
            public bool ShowRaw;
        }

        ConsoleErrorRules _rules;
        string _loadError;
        readonly List<Group> _groups = new List<Group>();
        Vector2 _scroll;
        bool _includeWarnings;
        bool _showIgnored;
        string _source = "";
        string _readError;

        GUIStyle _wrap, _title, _badge, _small, _raw;
        Group _copiedGroup;
        double _copiedAt;
        const float NarrowWidth = 520f;
        const double CopiedSeconds = 8;
        // 改行位置をこちらで決めた結果のキャッシュ（幅が変わったら作り直す）
        readonly Dictionary<string, string> _fitCache = new Dictionary<string, string>();
        float _fitWidth;

        /// <summary>文字幅を測って改行を入れる。reserve はバッジなど同じ行に並ぶものの幅。</summary>
        string Fit(string text, GUIStyle style, float reserve = 0f)
        {
            if (string.IsNullOrEmpty(text)) return text;
            // スクロールバー・枠の余白・ラベルの余白の分を引く（少し狭めにして Unity 側の再改行を避ける）
            float width = position.width - 56f - reserve;
            if (Mathf.Abs(width + reserve - _fitWidth) > 0.5f) { _fitCache.Clear(); _fitWidth = width + reserve; }
            var key = style.fontSize + "|" + reserve + "|" + text;
            if (!_fitCache.TryGetValue(key, out var result))
            {
                result = ErrorGuideText.WrapToWidth(ErrorGuideText.Wrap(text), t => style.CalcSize(new GUIContent(t)).x, width);
                _fitCache[key] = result;
            }
            return result;
        }

        public const string MenuPath = "Tools/Avatar Refinery/Console Errors (エラーの解説)";

        [MenuItem(MenuPath, priority = 20)]
        public static void Open()
        {
            var w = GetWindow<ConsoleErrorWindow>();
            w.titleContent = new GUIContent(ErrorGuideText.T("Console のエラー", "Console Errors"));
            w.minSize = new Vector2(420, 300);
            w.ReadFromConsole();
        }

        void OnEnable()
        {
            try { _rules = ConsoleErrorRules.LoadFromProject(); _loadError = null; }
            catch (Exception e) { _loadError = e.Message; }
        }

        void EnsureStyles()
        {
            if (_wrap != null) return;
            _wrap = new GUIStyle(EditorStyles.label) { wordWrap = true, richText = false };
            _title = new GUIStyle(EditorStyles.boldLabel) { wordWrap = true, fontSize = 13 };
            _badge = new GUIStyle(EditorStyles.miniBoldLabel) { alignment = TextAnchor.MiddleCenter, normal = { textColor = Color.white } };
            _small = new GUIStyle(EditorStyles.miniLabel) { wordWrap = true };
            _raw = new GUIStyle(EditorStyles.textArea) { wordWrap = true, fontSize = 10 };
        }

        void ReadFromConsole()
        {
            _readError = null;
            try { Build(ConsoleReader.ReadConsole(_includeWarnings)); _source = ErrorGuideText.T("Console（今表示されている内容）", "Console (what is shown now)"); }
            catch (Exception e) { _groups.Clear(); _readError = e.Message; }
        }

        void ReadFromLog()
        {
            _readError = null;
            var path = ConsoleReader.EditorLogPath();
            try { Build(ConsoleReader.ReadEditorLog(path, _includeWarnings)); _source = ErrorGuideText.T("Editor.log（この Unity を起動してからの記録）", "Editor.log (since this Unity session started)"); }
            catch (Exception e) { _groups.Clear(); _readError = ErrorGuideText.T("Editor.log を読めませんでした: ", "Could not read Editor.log: ") + e.Message; }
        }

        void Build(List<ConsoleItem> items)
        {
            _groups.Clear();
            if (_rules == null) return;
            var byRule = new Dictionary<string, Group>();
            foreach (var item in items)
            {
                var rule = _rules.Match(item.Message);
                if (rule == null)
                {
                    // 未登録は 1件ずつ見せる（まとめると中身が分からなくなるため）
                    _groups.Add(new Group { Rule = null, Items = { item } });
                    continue;
                }
                if (!byRule.TryGetValue(rule.id, out var g)) { g = new Group { Rule = rule }; byRule[rule.id] = g; _groups.Add(g); }
                g.Items.Add(item);
            }
            // 対処が必要 → 確認 → 未登録 → 無視してよい の順に並べる
            _groups.Sort((a, b) => Order(a).CompareTo(Order(b)));
        }

        static int Order(Group g)
        {
            if (g.Rule == null) return 2;
            switch (g.Rule.Level) { case ErrorLevel.Fix: return 0; case ErrorLevel.Check: return 1; default: return 3; }
        }

        void Update()
        {
            // 「コピーしました」を3秒後に消すため、その間だけ再描画する
            if (_copiedGroup != null && EditorApplication.timeSinceStartup - _copiedAt < CopiedSeconds + 0.5) Repaint();
        }

        void OnGUI()
        {
            EnsureStyles();
            // 言語を切り替えたらタブ名も合わせる
            var tabTitle = ErrorGuideText.T("Console のエラー", "Console Errors");
            if (titleContent.text != tabTitle) titleContent = new GUIContent(tabTitle);
            if (_loadError != null) { EditorGUILayout.HelpBox(_loadError, MessageType.Error); return; }

            using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
            {
                if (GUILayout.Button(ErrorGuideText.T("Console を読む", "Read Console"), EditorStyles.toolbarButton, GUILayout.Width(100))) ReadFromConsole();
                if (GUILayout.Button(ErrorGuideText.T("Editor.log から読む", "Read Editor.log"), EditorStyles.toolbarButton, GUILayout.Width(120))) ReadFromLog();
                GUILayout.FlexibleSpace();
                var w = GUILayout.Toggle(_includeWarnings, ErrorGuideText.T("黄色の警告も見る", "Include warnings"), EditorStyles.toolbarButton);
                if (w != _includeWarnings) { _includeWarnings = w; ReadFromConsole(); }
            }

            if (_readError != null) EditorGUILayout.HelpBox(_readError, MessageType.Warning);

            int fix = _groups.Where(g => g.Rule?.Level == ErrorLevel.Fix).Sum(g => g.Total);
            int check = _groups.Where(g => g.Rule?.Level == ErrorLevel.Check).Sum(g => g.Total);
            int unknown = _groups.Where(g => g.Rule == null).Sum(g => g.Total);
            int ignore = _groups.Where(g => g.Rule?.Level == ErrorLevel.Ignore).Sum(g => g.Total);

            EditorGUILayout.Space(4);
            if (fix + check + unknown + ignore == 0)
            {
                EditorGUILayout.HelpBox(ErrorGuideText.Wrap(ErrorGuideText.T("エラーは見つかりませんでした。\n（Console を Clear した後なら、「Editor.log から読む」で過去の分を確認できます）", "No errors found.\n(If you cleared the Console, use Read Editor.log to check earlier messages.)")), MessageType.Info);
                return;
            }
            EditorGUILayout.LabelField(ErrorGuideText.IsEnglish ? $"Fix: {fix} / Check: {check} / Not in dictionary: {unknown} / Safe to ignore: {ignore}" : $"対処が必要 {fix}件 ／ 確認 {check}件 ／ 未登録 {unknown}件 ／ 無視してよい {ignore}件", EditorStyles.boldLabel);
            EditorGUILayout.LabelField(ErrorGuideText.T("読み込み元: ", "Source: ") + _source, _small);
            _showIgnored = EditorGUILayout.ToggleLeft(ErrorGuideText.IsEnglish ? $"Show \"safe to ignore\" items ({ignore})" : $"「無視してよい」も表示する（{ignore}件）", _showIgnored);
            EditorGUILayout.Space(4);

            _scroll = EditorGUILayout.BeginScrollView(_scroll);
            foreach (var g in _groups)
            {
                if (g.Rule != null && g.Rule.Level == ErrorLevel.Ignore && !_showIgnored) continue;
                DrawGroup(g);
            }
            EditorGUILayout.Space(8);
            EditorGUILayout.LabelField(ErrorGuideText.IsEnglish ? $"Dictionary v{_rules.Version}, {_rules.Rules.Count} entries. Explanations are guidance only. Back up your project before making changes." : $"辞書 v{_rules.Version}・{_rules.Rules.Count}種類。説明は目安です。直す前にプロジェクトのバックアップを取ってください。", _small);
            EditorGUILayout.EndScrollView();
        }

        void DrawGroup(Group g)
        {
            using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
            {
                var title = g.Rule != null ? g.Rule.Title : ErrorGuideText.T("辞書にないエラー", "Error not in the dictionary");
                var headingText = (g.Total > 1 ? (ErrorGuideText.IsEnglish ? $"{title} ({g.Total})" : $"{title}（{g.Total}件）") : title);
                // 狭い幅では見出しを次の行に全幅で出す（バッジの横だと単語の途中で切れやすい）
                bool narrow = position.width < NarrowWidth;
                using (new EditorGUILayout.HorizontalScope())
                {
                    var (label, color) = Badge(g);
                    var rect = GUILayoutUtility.GetRect(new GUIContent(label), _badge, GUILayout.Width(84), GUILayout.Height(18));
                    EditorGUI.DrawRect(rect, color);
                    GUI.Label(rect, label, _badge);
                    GUILayout.Space(6);
                    if (!narrow) GUILayout.Label(Fit(headingText, _title, 96f), _title);
                }
                if (narrow) GUILayout.Label(Fit(headingText, _title), _title);

                if (g.Rule != null)
                {
                    Section(ErrorGuideText.T("どんなときに出る", "When it appears"), g.Rule.When);
                    Section(ErrorGuideText.T("原因", "Cause"), g.Rule.Cause);
                    var steps = g.Rule.Fix;
                    if (steps != null && steps.Length > 0)
                    {
                        GUILayout.Label(ErrorGuideText.T("直し方", "How to fix"), EditorStyles.miniBoldLabel);
                        for (int i = 0; i < steps.Length; i++) GUILayout.Label(Fit($"{i + 1}. {steps[i]}", _wrap), _wrap);
                    }
                }
                else
                {
                    GUILayout.Label(Fit(ErrorGuideText.T("この辞書ではまだ説明できないエラーです。下のボタンで、環境情報つきの質問文をコピーできます。配布元や Discord などに聞くときに、そのまま貼れます（ユーザー名の入ったパスは伏せてあります）。", "This dictionary cannot explain this error yet. Use the button below to copy a question with your environment details, ready to paste when asking the distributor or a Discord community (paths containing your user name are masked)."), _wrap), _wrap);
                }

                using (new EditorGUILayout.HorizontalScope())
                {
                    g.ShowRaw = EditorGUILayout.Foldout(g.ShowRaw, ErrorGuideText.T("元のエラー文", "Original message"), true);
                    GUILayout.FlexibleSpace();
                    if (_copiedGroup == g && EditorApplication.timeSinceStartup - _copiedAt < CopiedSeconds)
                        GUILayout.Label(ErrorGuideText.T("コピーしました", "Copied"), EditorStyles.miniBoldLabel, GUILayout.Width(80));
                    if (GUILayout.Button(ErrorGuideText.T("質問用の文をコピー", "Copy question text"), GUILayout.Width(130)))
                    {
                        EditorGUIUtility.systemCopyBuffer = EnvironmentInfo.QuestionText(g.Items[0].Message);
                        _copiedGroup = g;
                        _copiedAt = EditorApplication.timeSinceStartup;
                    }
                }
                if (g.ShowRaw)
                {
                    foreach (var it in g.Items.Take(5))
                        EditorGUILayout.SelectableLabel(Clip(it.Message, 1500), _raw, GUILayout.MinHeight(36), GUILayout.ExpandHeight(false));
                    if (g.Items.Count > 5) GUILayout.Label(ErrorGuideText.IsEnglish ? $"{g.Items.Count - 5} more" : $"ほか {g.Items.Count - 5} 種類", _small);
                }
            }
        }

        void Section(string head, string body)
        {
            if (string.IsNullOrEmpty(body)) return;
            GUILayout.Label(head, EditorStyles.miniBoldLabel);
            GUILayout.Label(Fit(body, _wrap), _wrap);
        }

        static (string, Color) Badge(Group g)
        {
            if (g.Rule == null) return (ErrorGuideText.T("未登録", "Unknown"), new Color(0.45f, 0.45f, 0.5f));
            switch (g.Rule.Level)
            {
                case ErrorLevel.Fix: return (ErrorGuideText.T("対処が必要", "Fix"), new Color(0.78f, 0.22f, 0.2f));
                case ErrorLevel.Check: return (ErrorGuideText.T("確認", "Check"), new Color(0.85f, 0.55f, 0.1f));
                default: return (ErrorGuideText.T("無視してよい", "Ignore"), new Color(0.25f, 0.55f, 0.35f));
            }
        }

        static string Clip(string s, int max) => s.Length <= max ? s : s.Substring(0, max) + "\n…";
    }
}
