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

namespace Jovian.TagSystem.Editor {
    [CustomEditor(typeof(JovianTagsSettings))]
    public class JovianTagsSettingsInspector : UnityEditor.Editor {
        public override void OnInspectorGUI() {
            serializedObject.Update();
            DrawDefaultInspector();

            var settings = (JovianTagsSettings)target;

            // Validate and show errors
            var errors = ValidateTags(settings);
            if(errors.Count > 0) {
                GUILayout.Space(4);
                foreach(var error in errors) {
                    EditorGUILayout.HelpBox(error, MessageType.Error);
                }
            }

            GUILayout.Space(8);

            EditorGUILayout.BeginHorizontal();

            var prevBg = GUI.backgroundColor;
            GUI.backgroundColor = new Color(0.3f, 0.8f, 0.3f);
            if(GUILayout.Button("Save & Generate Tags", GUILayout.Height(28))) {
                CleanAndSave(settings);
                JovianTagsGenerator.Regenerate();
            }

            GUI.backgroundColor = prevBg;

            if(GUILayout.Button("Open Tag Editor", GUILayout.Height(28))) {
                JovianTagsEditorWindow.ShowWindow();
            }

            EditorGUILayout.EndHorizontal();
        }

        private static List<string> ValidateTags(JovianTagsSettings settings) {
            var errors = new List<string>();
            var seen = new HashSet<string>(System.StringComparer.Ordinal);

            foreach(var t in settings.gameTags) {
                if(string.IsNullOrWhiteSpace(t.tag)) {
                    errors.Add("Empty tag name found.");
                    continue;
                }

                var segmentError = JovianTagsGenerator.ValidateTagName(t.tag);
                if(segmentError != null) {
                    errors.Add($"'{t.tag}': {segmentError}");
                    continue;
                }

                if(!seen.Add(t.tag)) {
                    errors.Add($"Duplicate tag '{t.tag}' — will be removed on Save & Generate.");
                }
            }

            return errors;
        }

        private static void CleanAndSave(JovianTagsSettings settings) {
            var seen = new HashSet<string>(System.StringComparer.Ordinal);
            var cleaned = new List<RegisteredTag>();
            var removed = 0;

            foreach(var t in settings.gameTags) {
                if(string.IsNullOrWhiteSpace(t.tag)) {
                    removed++;
                    continue;
                }

                if(JovianTagsGenerator.ValidateTagName(t.tag) != null) {
                    removed++;
                    continue;
                }

                if(!seen.Add(t.tag)) {
                    removed++;
                    continue;
                }

                cleaned.Add(t);
            }

            if(removed > 0) {
                Undo.RecordObject(settings, "Clean Game Tags");
                settings.gameTags = cleaned.ToArray();
                Debug.Log($"[GameTagSettings] Cleaned {removed} invalid/duplicate tag(s).");
            }

            EditorUtility.SetDirty(settings);
            AssetDatabase.SaveAssets();
        }
    }
}
