using System.IO;
using UnityEditor;
using UnityEngine;

namespace ViKPI.Editor
{
    /// <summary>Project Settings → ViKPI. Creates the settings asset on first use.</summary>
    internal static class VikpiSettingsProvider
    {
        private const string AssetFolder = "Assets/ViKPI Settings/Resources";
        private const string AssetPath = AssetFolder + "/" + VikpiSettings.ResourceName + ".asset";
        private const string DashboardUrl = "https://vikpi.com";

        internal static VikpiSettings GetOrCreate()
        {
            var settings = VikpiSettings.Load();
            if (settings != null) return settings;
            settings = AssetDatabase.LoadAssetAtPath<VikpiSettings>(AssetPath);
            if (settings != null) return settings;

            Directory.CreateDirectory(AssetFolder);
            settings = ScriptableObject.CreateInstance<VikpiSettings>();
            AssetDatabase.CreateAsset(settings, AssetPath);
            AssetDatabase.SaveAssets();
            return settings;
        }

        [SettingsProvider]
        private static SettingsProvider Create()
        {
            SerializedObject so = null;
            return new SettingsProvider("Project/ViKPI", SettingsScope.Project)
            {
                label = "ViKPI",
                keywords = new[] { "vikpi", "analytics", "session replay", "heatmap", "api key" },
                activateHandler = (_, __) => so = new SerializedObject(GetOrCreate()),
                guiHandler = _ =>
                {
                    if (so == null || so.targetObject == null) so = new SerializedObject(GetOrCreate());
                    so.Update();
                    Draw(so);
                    so.ApplyModifiedProperties();
                },
            };
        }

        private static void Draw(SerializedObject so)
        {
            var labelWidth = EditorGUIUtility.labelWidth;
            EditorGUIUtility.labelWidth = 200;

            EditorGUILayout.Space(6);
            EditorGUILayout.LabelField("Connection", EditorStyles.boldLabel);
            var key = so.FindProperty("apiKey");
            EditorGUILayout.PropertyField(key, new GUIContent("API Key"));
            if (string.IsNullOrWhiteSpace(key.stringValue))
            {
                EditorGUILayout.HelpBox("Paste the key from your project in the dashboard: Project settings → API keys.", MessageType.Info);
                if (GUILayout.Button("Open the dashboard", GUILayout.Width(180))) Application.OpenURL(DashboardUrl);
            }
            else if (!key.stringValue.Trim().StartsWith("vk_pub_"))
            {
                EditorGUILayout.HelpBox("Keys start with vk_pub_. Check you copied the whole key.", MessageType.Warning);
            }
            EditorGUILayout.PropertyField(so.FindProperty("endpoint"));
            EditorGUILayout.PropertyField(so.FindProperty("autoStart"));
            EditorGUILayout.PropertyField(so.FindProperty("runInEditor"), new GUIContent("Run In Editor"));

            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Privacy (required for Google Play and the App Store)", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(so.FindProperty("privacyPolicyUrl"), new GUIContent("Privacy Policy URL"));
            EditorGUILayout.PropertyField(so.FindProperty("consentMode"));
            var mode = (VikpiConsentMode)so.FindProperty("consentMode").enumValueIndex;
            switch (mode)
            {
                case VikpiConsentMode.BuiltInPrompt:
                    EditorGUILayout.HelpBox("Players see a short prompt on first launch; nothing is collected unless they tap Allow. " +
                                            "Add a \"Privacy\" button in your settings that calls Vikpi.ShowConsentPrompt() so they can change their mind.", MessageType.None);
                    break;
                case VikpiConsentMode.Manual:
                    EditorGUILayout.HelpBox("Nothing is collected until your game calls Vikpi.SetConsent(true), e.g. from your own dialog or consent platform.", MessageType.None);
                    break;
                default:
                    EditorGUILayout.HelpBox("Players are recorded without being asked. Use only if your game already has another legal basis and discloses screen recording.", MessageType.Warning);
                    break;
            }
            EditorGUILayout.PropertyField(so.FindProperty("appTargetsChildren"), new GUIContent("App Targets Children"));
            EditorGUILayout.PropertyField(so.FindProperty("maskTextInputs"), new GUIContent("Mask Text Inputs"));
            if (mode == VikpiConsentMode.BuiltInPrompt)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(so.FindProperty("consentTitle"), new GUIContent("Prompt Title"));
                EditorGUILayout.PropertyField(so.FindProperty("consentMessage"), new GUIContent("Prompt Message"));
                EditorGUILayout.PropertyField(so.FindProperty("consentAcceptLabel"), new GUIContent("Allow Button"));
                EditorGUILayout.PropertyField(so.FindProperty("consentDeclineLabel"), new GUIContent("Refuse Button"));
                EditorGUILayout.PropertyField(so.FindProperty("consentPolicyLabel"), new GUIContent("Policy Link"));
                EditorGUI.indentLevel--;
            }
            so.ApplyModifiedProperties();
            var errors = VikpiBuildValidator.Check((VikpiSettings)so.targetObject, out var warnings);
            foreach (var e in errors) EditorGUILayout.HelpBox(e + " Builds fail until this is fixed.", MessageType.Error);
            foreach (var w in warnings) EditorGUILayout.HelpBox(w, MessageType.Warning);
            if (GUILayout.Button("What to declare on Google Play and the App Store", GUILayout.Width(330)))
                Application.OpenURL(VikpiBuildValidator.DocsUrl);

            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Collect", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(so.FindProperty("allowRecording"), new GUIContent("Session Video"));
            EditorGUILayout.PropertyField(so.FindProperty("trackTouches"), new GUIContent("Touches"));
            EditorGUILayout.PropertyField(so.FindProperty("trackPerformance"), new GUIContent("Performance"));
            EditorGUILayout.PropertyField(so.FindProperty("captureErrors"), new GUIContent("Errors And Exceptions"));
            EditorGUILayout.HelpBox(
                "Video sample rate, frame rate and quality are set per project in the dashboard, so you can change them without a new build. " +
                "Text input fields are masked automatically (Mask Text Inputs). Add a ViKPI/Recording Mask component to anything else " +
                "that shows personal data (profiles, chat, payment screens); it is blacked out on the device before encoding.",
                MessageType.None);

            EditorGUILayout.Space(10);
            EditorGUILayout.LabelField("Advanced", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(so.FindProperty("sessionTimeoutSeconds"), new GUIContent("Session Timeout (s)"));
            EditorGUILayout.PropertyField(so.FindProperty("maxOfflineStorageMb"), new GUIContent("Offline Storage (MB)"));
            EditorGUILayout.PropertyField(so.FindProperty("debugLogging"));

            EditorGUIUtility.labelWidth = labelWidth;
        }

        [MenuItem("Tools/ViKPI/Settings", priority = 1)]
        private static void OpenSettings() => SettingsService.OpenProjectSettings("Project/ViKPI");

        [MenuItem("Tools/ViKPI/Open Dashboard", priority = 2)]
        private static void OpenDashboard() => Application.OpenURL(DashboardUrl);
    }
}
