#region Header

// Copyright (c) 2026 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.

#endregion

using UnityEditor;
using UnityEngine;

#if UNITY_EDITOR
namespace BlackBox
{
    public class BlackBoxHelperDownloadWindow : EditorWindow
    {
        private static readonly Vector2 WINDOW_SIZE = new(460, 470);

        private const string BLACKBOX_LOGO_ASSET = "Assets/Plugins/BlackBoxUnitySDK/BlackBox/Resources/blackbox_logo.png";
        private Texture2D _logoTexture;
        private bool _downloadStarted;

        private bool _crashHelperExpanded;
        private bool _issueReporterExpanded;

        public static void Open()
        {
            var window = GetWindow<BlackBoxHelperDownloadWindow>(true, "BlackBox Helper Setup");
            window.minSize = WINDOW_SIZE;
            window.maxSize = WINDOW_SIZE;
            window.Show();
        }

        private void OnEnable()
        {
            _logoTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(BLACKBOX_LOGO_ASSET);
        }

        private void OnDestroy()
        {
            if (!_downloadStarted)
                BlackBoxHelperInstaller.MarkDismissed();
        }

        private void OnGUI()
        {
            GUILayout.Space(16);

            DrawLogo();
            GUILayout.Space(12);

            DrawHeader();
            GUILayout.Space(12);

            DrawDescription();
            GUILayout.Space(10);

            DrawDependencies();
            GUILayout.FlexibleSpace();

            DrawDownloadButton();
            GUILayout.Space(12);
        }

        private void DrawLogo()
        {
            if (_logoTexture == null)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.FlexibleSpace();
                }
                return;
            }

            float maxHeight = 80f;
            float scale = Mathf.Min(1f, maxHeight / _logoTexture.height);
            float drawWidth = _logoTexture.width * scale;
            float drawHeight = _logoTexture.height * scale;

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                GUILayout.Label(_logoTexture, GUILayout.Width(drawWidth), GUILayout.Height(drawHeight));
                GUILayout.FlexibleSpace();
            }
        }

        private void DrawHeader()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                GUILayout.Label("BlackBox Helper Setup", EditorStyles.boldLabel);
                GUILayout.FlexibleSpace();
            }
        }

        private void DrawDescription()
        {
            GUILayout.Label(
                "BlackBox requires helper tools for crash reporting and issue submission.\n" +
                "Please download the required executables to complete the setup."
                , EditorStyles.centeredGreyMiniLabel);
        }

        private void DrawDependencies()
        {
            GUILayout.Label("Dependencies", EditorStyles.boldLabel);
            EditorGUILayout.Space(3);

            EditorGUILayout.HelpBox(
                "The following tools are required:",
                MessageType.Warning
            );
            EditorGUILayout.Space(5);

            _crashHelperExpanded = DrawDependencyItem(_crashHelperExpanded, $"BlackBox Helper v{BlackBoxHelperInstaller.CRASH_HELPER_VERSION}", "blackbox_helper.exe (~13 MB)", "Automatically captures crash data, logs, and gameplay video to help developers reproduce and fix errors quickly.");
            EditorGUILayout.Space(2);

            _issueReporterExpanded = DrawDependencyItem(_issueReporterExpanded, $"BlackBox Issue Reporter v{BlackBoxHelperInstaller.ISSUE_REPORTER_VERSION}", "blackbox_issue_reporter.exe (~5 MB)", "A manual reporting tool for capturing screenshots and submitting detailed bug reports or feedback.");
            EditorGUILayout.Space(2);
        }

        private bool DrawDependencyItem(bool expanded, string name, string file, string description)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                string arrow = expanded ? " ▼ " : " ▶ ";
                if (GUILayout.Button(arrow, EditorStyles.toolbarButton, GUILayout.Width(20), GUILayout.Height(22)))
                {
                    expanded = !expanded;
                }

                GUILayout.Label(name, GUILayout.Width(200), GUILayout.Height(22));
                GUILayout.Label(file, EditorStyles.miniLabel);
            }

            if (expanded)
            {
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                EditorGUILayout.Space(4);

                EditorGUILayout.LabelField(description, new GUIStyle(EditorStyles.wordWrappedLabel)
                {
                    fontSize = 11,
                    normal = { textColor = new Color(0.75f, 0.75f, 0.75f) }
                });

                var linkStyle = new GUIStyle(EditorStyles.label)
                {
                    fontSize = 9,
                    normal = { textColor = new Color(0.24f, 0.49f, 0.90f) },
                    hover = { textColor = new Color(0.35f, 0.62f, 1.0f) }
                };
                var rect = GUILayoutUtility.GetRect(
                    new GUIContent("Documentation"),
                    linkStyle
                );

                EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);

                if (GUI.Button(rect, "Documentation", linkStyle))
                {
                    if (name.Contains("BlackBox Helper"))
                        Application.OpenURL("https://docs.accelbyte.io/development-toolkit/developer-guides/blackbox-error-reporter/unity-crash-reporter/");
                    else if (name.Contains("BlackBox Issue Reporter"))
                        Application.OpenURL("https://docs.accelbyte.io/development-toolkit/developer-guides/blackbox-error-reporter/Issue%20Reporter/");
                }
                EditorGUILayout.Space(4);
                EditorGUILayout.EndVertical();
            }

            return expanded;
        }

        private void DrawDownloadButton()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();

                GUIStyle downloadButtonStyle = new GUIStyle(GUI.skin.button)
                {
                    fontSize = 20,
                    fontStyle = FontStyle.Bold,
                    alignment = TextAnchor.MiddleCenter,
                };

                if (GUILayout.Button("Download", downloadButtonStyle, GUILayout.Height(36), GUILayout.Width(160)))
                {
                    _downloadStarted = true;
                    Close();
                    BlackBoxHelperInstaller.StartDownloadFromUI();
                }

                GUILayout.FlexibleSpace();
            }
        }
    }
}
#endif