using System;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace Woop.Unity.Editor
{
    public sealed class WoopToolWindow : EditorWindow
    {
        private const string WebsiteUrl = "https://piying.woooostudio.com/";
        private const string LastImportDirectoryKey = "Woop.Unity.LastImportDirectory";
        private const string DefaultImportFolder = "Assets/Woop";

        private Texture2D logo;
        private GUIStyle titleStyle;
        private GUIStyle bodyStyle;
        private GUIStyle primaryButtonStyle;
        private GUIStyle secondaryButtonStyle;

        [MenuItem("Woop/打开工具面板", priority = 1)]
        [MenuItem("Window/Woop 工具面板", priority = 2200)]
        public static void Open()
        {
            WoopToolWindow window = GetWindow<WoopToolWindow>();
            window.titleContent = new GUIContent("Woop");
            window.minSize = new Vector2(420f, 380f);
            window.Show();
        }

        private void OnEnable()
        {
            titleContent = new GUIContent("Woop");
            LoadLogo();
        }

        private void OnGUI()
        {
            EnsureStyles();

            float contentWidth = Mathf.Max(320f, position.width - 40f);
            using (new GUILayout.VerticalScope())
            {
                DrawLogo(contentWidth);

                GUILayout.Space(18f);
                GUILayout.Label("Woop 皮影角色工具", titleStyle);
                GUILayout.Space(6f);
                GUILayout.Label("将 .woop 角色导入项目，并自动生成可操作的 2D 骨骼角色。", bodyStyle);
                GUILayout.Space(22f);

                using (new GUILayout.HorizontalScope())
                {
                    GUILayout.Space(20f);
                    using (new GUILayout.VerticalScope())
                    {
                        if (GUILayout.Button("导入 WOOP", primaryButtonStyle, GUILayout.Height(48f)))
                            ImportWoop();

                        GUILayout.Space(10f);
                        if (GUILayout.Button("访问官网", secondaryButtonStyle, GUILayout.Height(42f)))
                            Application.OpenURL(WebsiteUrl);
                    }
                    GUILayout.Space(20f);
                }

                GUILayout.FlexibleSpace();
                GUILayout.Space(14f);
                GUILayout.Label("WooooStudio 五天晴工作室  ·  Make Something Woooo~", bodyStyle);
                GUILayout.Space(16f);
            }
        }

        private void DrawLogo(float contentWidth)
        {
            const float aspect = 1332f / 416f;
            float width = Mathf.Min(contentWidth, 760f);
            float height = width / aspect;
            Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(true));

            if (logo != null)
            {
                GUI.DrawTexture(rect, logo, ScaleMode.ScaleToFit, false);
                return;
            }

            EditorGUI.HelpBox(rect, "Woop", MessageType.None);
        }

        private void LoadLogo()
        {
            MonoScript script = MonoScript.FromScriptableObject(this);
            if (script == null)
                return;

            string scriptPath = AssetDatabase.GetAssetPath(script);
            string directory = Path.GetDirectoryName(scriptPath)?.Replace('\\', '/');
            if (!string.IsNullOrEmpty(directory))
                logo = AssetDatabase.LoadAssetAtPath<Texture2D>($"{directory}/WoopLogo.png");
        }

        private void EnsureStyles()
        {
            if (titleStyle != null)
                return;

            titleStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                alignment = TextAnchor.MiddleCenter,
                fontSize = 21,
                wordWrap = true
            };
            bodyStyle = new GUIStyle(EditorStyles.label)
            {
                alignment = TextAnchor.MiddleCenter,
                fontSize = 12,
                wordWrap = true
            };
            primaryButtonStyle = new GUIStyle(GUI.skin.button)
            {
                fontSize = 15,
                fontStyle = FontStyle.Bold
            };
            secondaryButtonStyle = new GUIStyle(GUI.skin.button)
            {
                fontSize = 13
            };
        }

        private void ImportWoop()
        {
            string initialDirectory = EditorPrefs.GetString(LastImportDirectoryKey, string.Empty);
            string sourcePath = EditorUtility.OpenFilePanel("导入 WOOP", initialDirectory, "woop");
            if (string.IsNullOrEmpty(sourcePath))
                return;

            EditorPrefs.SetString(LastImportDirectoryKey, Path.GetDirectoryName(sourcePath) ?? string.Empty);
            EnsureAssetFolder(DefaultImportFolder);

            string destinationPath = AssetDatabase.GenerateUniqueAssetPath(
                $"{DefaultImportFolder}/{Path.GetFileName(sourcePath)}");
            string projectRoot = Directory.GetParent(Application.dataPath)?.FullName
                ?? throw new InvalidOperationException("无法确定 Unity 项目目录。");
            string absoluteDestinationPath = Path.Combine(projectRoot, destinationPath);

            try
            {
                File.Copy(sourcePath, absoluteDestinationPath, false);
                AssetDatabase.ImportAsset(destinationPath, ImportAssetOptions.ForceSynchronousImport);

                UnityEngine.Object importedAsset = AssetDatabase.LoadMainAssetAtPath(destinationPath);
                Selection.activeObject = importedAsset;
                EditorGUIUtility.PingObject(importedAsset);
                ShowNotification(new GUIContent($"已导入：{Path.GetFileName(destinationPath)}"));
            }
            catch (Exception exception)
            {
                Debug.LogException(exception);
                EditorUtility.DisplayDialog("WOOP 导入失败", exception.Message, "确定");
            }
        }

        private static void EnsureAssetFolder(string assetFolder)
        {
            if (AssetDatabase.IsValidFolder(assetFolder))
                return;

            string[] segments = assetFolder.Split('/');
            string current = segments[0];
            for (int index = 1; index < segments.Length; index++)
            {
                string next = $"{current}/{segments[index]}";
                if (!AssetDatabase.IsValidFolder(next))
                    AssetDatabase.CreateFolder(current, segments[index]);
                current = next;
            }
        }
    }
}
