using System;
using Alibabacloud.Rum.Unity.Logs;
using UnityEditor;
using UnityEngine;

namespace Alibabacloud.Rum.Unity.Editor
{
    internal static class CoreTab
    {
        internal static void Display(AlibabacloudOptions options)
        {
            {
                // Render endpoint / id / workspace fields differently per build target.
                //  - Windows Standalone (native C SDK): CONFIG ADDRESS + APP ID
                //  - Android / iOS / WebGL (managed SDK): Endpoint + SERVICE ID + WORKSPACE
                // Both branches store values in the same underlying fields
                // (options.Endpoint / options.ServiceId) so a single ScriptableObject
                // works across platforms; only the labels and tooltips differ.
                var target = EditorUserBuildSettings.activeBuildTarget;
                bool isWindowsStandalone = target == BuildTarget.StandaloneWindows
                                           || target == BuildTarget.StandaloneWindows64;

                EditorGUILayout.LabelField(
                    isWindowsStandalone ? "Build Target: Windows Standalone" : $"Build Target: {target}",
                    EditorStyles.miniBoldLabel);

                if (isWindowsStandalone)
                {
                    // The Windows native SDK expects the *full* config address
                    // (e.g. "https://example.com/rum/web/v2"). To keep the UX
                    // simple, the user only types the base endpoint here and we
                    // automatically append the fixed "/rum/web/v2" suffix when
                    // saving back to options.Endpoint. On re-open we strip the
                    // suffix before showing so editing remains idempotent.
                    const string windowsConfigSuffix = "/rum/web/v2";

                    string rawEndpoint = options.Endpoint ?? string.Empty;
                    if (rawEndpoint.EndsWith(windowsConfigSuffix, StringComparison.Ordinal))
                    {
                        rawEndpoint = rawEndpoint.Substring(
                            0, rawEndpoint.Length - windowsConfigSuffix.Length);
                    }

                    string newEndpoint = EditorGUILayout.TextField(
                        new GUIContent("Endpoint",
                            "Base endpoint URL of your Alibabacloud RUM project. " +
                            "The fixed suffix \"/rum/web/v2\" will be appended automatically " +
                            "when passed to alibabacloud_rum_options_set_config_address."),
                        rawEndpoint)?.Trim() ?? string.Empty;

                    if (string.IsNullOrWhiteSpace(newEndpoint))
                    {
                        options.Endpoint = string.Empty;
                        EditorGUILayout.HelpBox("The SDK requires an endpoint.", MessageType.Error);
                    }
                    else
                    {
                        // Normalize trailing slash to avoid producing
                        // "host//rum/web/v2".
                        options.Endpoint = newEndpoint.TrimEnd('/') + windowsConfigSuffix;
                        EditorGUILayout.HelpBox(
                            "Final config address: " + options.Endpoint, MessageType.Info);
                    }

                    options.ServiceId = EditorGUILayout.TextField(
                        new GUIContent("APP ID",
                            "Application identifier registered in the Alibabacloud RUM console. " +
                            "Maps to alibabacloud_rum_options_set_app_id."),
                        options.ServiceId)?.Trim();
                    if (string.IsNullOrWhiteSpace(options.ServiceId))
                    {
                        EditorGUILayout.HelpBox("The SDK requires an APP ID.", MessageType.Error);
                    }

                    // Workspace is not consumed by the Windows native SDK, so we hide
                    // the input here to avoid confusing users.
                }
                else
                {
                    options.Endpoint = EditorGUILayout.TextField(
                        new GUIContent("Endpoint",
                            "The URL to your Alibabacloud Rum project. " +
                            "Get yours on arms.aliyun.com -> Project Settings."),
                        options.Endpoint)?.Trim();
                    if (string.IsNullOrWhiteSpace(options.Endpoint))
                    {
                        EditorGUILayout.HelpBox("The SDK requires a Endpoint.", MessageType.Error);
                    }

                    options.ServiceId = EditorGUILayout.TextField(
                        new GUIContent("SERVICE ID", "Service ID to use when connecting to the SDK."),
                        options.ServiceId)?.Trim();
                    if (string.IsNullOrWhiteSpace(options.ServiceId))
                    {
                        EditorGUILayout.HelpBox("The SDK requires a SERVICE ID.", MessageType.Error);
                    }

                    options.Workspace = EditorGUILayout.TextField(
                        new GUIContent("WORKSPACE", "Workspace to use when connecting to the SDK."),
                        options.Workspace)?.Trim();
                }

                // var sampleRate = EditorGUILayout.FloatField(
                //     new GUIContent("Event Sample Rate", "Indicates the percentage of events that are " +
                //                                         "captured. Setting this to 0.1 captures 10% of events. " +
                //                                         "Setting this to 1.0 captures all events." +
                //                                         "\nThis affects only errors and logs, not performance " +
                //                                         "(transactions) data. See TraceSampleRate for that."),
                //     options.SampleRate);
                // options.SampleRate = Mathf.Clamp01(sampleRate);

                options.EnableNativeSDKLogDebug = EditorGUILayout.Toggle(
                    new GUIContent("Enable Native SDK Debuggable", "Enable Native SDK Debuggable."),
                    options.EnableNativeSDKLogDebug);
            }

            EditorGUILayout.Space();
            EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.gray);
            EditorGUILayout.Space();

            {
                options.AutomaticSceneTracking = EditorGUILayout.Toggle(
                    new GUIContent("Automatic Scene Tracking", "Enable automatic view (scene) tracking. " +
                                                               "When enabled, scene changes will be automatically tracked as RUM views " +
                                                               "with scene path as view ID and scene name as view name."),
                    options.AutomaticSceneTracking);
            }

            EditorGUILayout.Space();
            EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.gray);
            EditorGUILayout.Space();

            {
                options.Debug = EditorGUILayout.BeginToggleGroup(
                    new GUIContent("Enable Debug Output", "Whether the Alibabacloud SDK should print its " +
                                                          "diagnostic logs to the console."),
                    options.Debug);

                EditorGUI.indentLevel++;
                // options.DebugOnlyInEditor = EditorGUILayout.Toggle(
                //     new GUIContent("Only In Editor", "Only print logs when in the editor. Development " +
                //                                      "builds of the player will not include Alibabacloud's SDK diagnostics."),
                //     options.DebugOnlyInEditor);

                options.DiagnosticLevel = (AlibabacloudLogLevel)EditorGUILayout.EnumPopup(
                    new GUIContent("Verbosity Level", "The minimum level allowed to be printed to the console. " +
                                                      "Log messages with a level below this level are dropped."),
                    options.DiagnosticLevel);

                EditorGUI.indentLevel--;
                EditorGUILayout.EndToggleGroup();
            }

            EditorGUILayout.Space();
            EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.gray);
            EditorGUILayout.Space();

            // // Symbol Files Section -- todo 暂时去掉，因为目前还用不上
            // {
            //     EditorGUILayout.LabelField("Symbol Files & Crash Symbolication", EditorStyles.boldLabel);
            //     EditorGUI.indentLevel++;
            //
            //     options.OutputSymbols = EditorGUILayout.ToggleLeft(
            //         new GUIContent("Output Symbol Files", 
            //             "Enable generation of IL2CPP symbol mapping files during build. " +
            //             "Required for proper stack trace symbolication on IL2CPP builds. " +
            //             "This adds '--emit-source-mapping' to IL2CPP arguments."),
            //         options.OutputSymbols);
            //
            //     if (options.OutputSymbols)
            //     {
            //         EditorGUI.indentLevel++;
            //         
            //         EditorGUILayout.HelpBox(
            //             "Symbol files will be generated in:\n" +
            //             "• Android: <GradleProject>/symbols/LineNumberMappings.json\n" +
            //             "• iOS: <XcodeProject>/alibabacloudSymbols/LineNumberMappings.json\n\n" +
            //             "A build_id file will also be created to correlate symbols with specific builds.",
            //             MessageType.Info);
            //
            //         EditorGUILayout.Space();
            //
            //         options.UploadSymbolsAfterBuild = EditorGUILayout.ToggleLeft(
            //             new GUIContent("Auto Upload After Build",
            //                 "Automatically upload symbol files to Alibabacloud after build completes. " +
            //                 "Requires valid API credentials."),
            //             options.UploadSymbolsAfterBuild);
            //
            //         if (options.UploadSymbolsAfterBuild)
            //         {
            //             EditorGUI.indentLevel++;
            //
            //             options.SymbolUploadEndpoint = EditorGUILayout.TextField(
            //                 new GUIContent("Upload Endpoint",
            //                     "API endpoint for symbol file upload. Leave empty to use default endpoint."),
            //                 options.SymbolUploadEndpoint)?.Trim();
            //
            //             options.SymbolUploadApiKey = EditorGUILayout.PasswordField(
            //                 new GUIContent("API Key",
            //                     "API key or access token for authentication. Keep this secure!"),
            //                 options.SymbolUploadApiKey ?? string.Empty)?.Trim();
            //
            //             if (string.IsNullOrWhiteSpace(options.SymbolUploadApiKey))
            //             {
            //                 EditorGUILayout.HelpBox(
            //                     "API Key is required for automatic symbol upload.",
            //                     MessageType.Warning);
            //             }
            //
            //             EditorGUI.indentLevel--;
            //         }
            //
            //         EditorGUI.indentLevel--;
            //     }
            //
            //     EditorGUI.indentLevel--;
            // }

            // EditorGUILayout.Space();
            // EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.gray);
            // EditorGUILayout.Space();

            
        }
    }
}
