using System.IO;
using UnityEditor;
using UnityEngine;

namespace AlterchaseSDK.Editor
{
    public class ModIOUploadWindow : EditorWindow
    {
        private ModPackage selectedPackage;
        private string email = "";
        private string securityCode = "";
        private bool isAuthenticated = false;
        private Vector2 scrollPosition;
        
        private enum UploadState
        {
            NotAuthenticated,
            WaitingForCode,
            Authenticated,
            Uploading,
            Complete
        }
        
        private UploadState currentState = UploadState.NotAuthenticated;

        // Direct upload feature has been disabled
        // [MenuItem("Alterchase SDK/Upload to mod.io", priority = 4)]
        // public static void ShowWindow()
        // {
        //     ModIOUploadWindow window = GetWindow<ModIOUploadWindow>("mod.io Upload");
        //     window.minSize = new Vector2(450, 400);
        //     window.Show();
        // }

        private void OnEnable()
        {
            CheckAuthentication();
        }

        private void OnGUI()
        {
            DrawHeader();
            
            EditorGUILayout.Space(10);
            
            DrawPackageSelection();
            
            EditorGUILayout.Space(10);
            
            switch (currentState)
            {
                case UploadState.NotAuthenticated:
                    DrawAuthenticationSection();
                    break;
                case UploadState.WaitingForCode:
                    DrawCodeSubmissionSection();
                    break;
                case UploadState.Authenticated:
                    DrawUploadSection();
                    break;
                case UploadState.Uploading:
                    DrawUploadingSection();
                    break;
                case UploadState.Complete:
                    DrawCompleteSection();
                    break;
            }
        }

        private void DrawHeader()
        {
            EditorGUILayout.LabelField("Upload Mod to mod.io", EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Publish your mod package to the mod.io platform.", EditorStyles.miniLabel);
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
        }

        private void DrawPackageSelection()
        {
            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.LabelField("Select Mod Package", EditorStyles.boldLabel);
            
            selectedPackage = EditorGUILayout.ObjectField("Mod Package:", selectedPackage, typeof(ModPackage), false) as ModPackage;
            
            if (selectedPackage != null)
            {
                EditorGUILayout.Space(5);
                EditorGUILayout.LabelField("Package Details:", EditorStyles.boldLabel);
                EditorGUILayout.LabelField($"Name: {selectedPackage.PackageName}");
                EditorGUILayout.LabelField($"Author: {selectedPackage.AuthorName}");
                EditorGUILayout.LabelField($"Version: {selectedPackage.Version}");
                EditorGUILayout.LabelField($"Total Assets: {selectedPackage.GetTotalAssetCount()}");
            }
            
            EditorGUILayout.EndVertical();
        }

        private void DrawAuthenticationSection()
        {
            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.LabelField("mod.io Authentication", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("Enter your email address to receive an authentication code from mod.io.", MessageType.Info);
            
            email = EditorGUILayout.TextField("Email:", email);
            
            if (GUILayout.Button("Request Authentication Code"))
            {
                RequestAuthCode();
            }
            
            EditorGUILayout.EndVertical();
        }

        private void DrawCodeSubmissionSection()
        {
            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.LabelField("Enter Security Code", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox($"A security code has been sent to {email}. Please check your email and enter the code below.", MessageType.Info);
            
            securityCode = EditorGUILayout.TextField("Security Code:", securityCode);
            
            EditorGUILayout.BeginHorizontal();
            
            if (GUILayout.Button("Submit Code"))
            {
                SubmitCode();
            }
            
            if (GUILayout.Button("Back"))
            {
                currentState = UploadState.NotAuthenticated;
                securityCode = "";
            }
            
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }

        private void DrawUploadSection()
        {
            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.LabelField("Upload Mod Package", EditorStyles.boldLabel);
            
            if (!isAuthenticated)
            {
                EditorGUILayout.HelpBox("You are not authenticated. Please authenticate first.", MessageType.Warning);
                return;
            }
            
            if (selectedPackage == null)
            {
                EditorGUILayout.HelpBox("Please select a mod package to upload.", MessageType.Warning);
                return;
            }
            
            EditorGUILayout.HelpBox("Ready to upload! Make sure you have built your asset bundles before uploading.", MessageType.Info);
            
            EditorGUILayout.Space(5);
            
            if (GUILayout.Button("Build Asset Bundles First", GUILayout.Height(30)))
            {
                ModPackageBuilder.ShowWindow();
            }
            
            EditorGUILayout.Space(5);
            
            if (GUILayout.Button("Upload to mod.io", GUILayout.Height(40)))
            {
                UploadMod();
            }
            
            EditorGUILayout.EndVertical();
        }

        private void DrawUploadingSection()
        {
            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.LabelField("Uploading...", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("Your mod is being uploaded to mod.io. Please wait...", MessageType.Info);
            EditorGUILayout.EndVertical();
        }

        private void DrawCompleteSection()
        {
            EditorGUILayout.BeginVertical("box");
            EditorGUILayout.LabelField("Upload Complete!", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("Your mod has been successfully uploaded to mod.io!", MessageType.Info);
            
            if (GUILayout.Button("Upload Another Mod"))
            {
                currentState = UploadState.Authenticated;
                selectedPackage = null;
            }
            
            EditorGUILayout.EndVertical();
        }

        private async void CheckAuthentication()
        {
            if (ModIOIntegration.Instance.IsAuthenticated)
            {
                isAuthenticated = true;
                currentState = UploadState.Authenticated;
            }
        }

        private async void RequestAuthCode()
        {
            if (string.IsNullOrEmpty(email))
            {
                EditorUtility.DisplayDialog("Error", "Please enter a valid email address.", "OK");
                return;
            }

            bool success = await ModIOIntegration.Instance.AuthenticateWithEmail(email);
            
            if (success)
            {
                currentState = UploadState.WaitingForCode;
            }
            else
            {
                EditorUtility.DisplayDialog("Error", "Failed to request authentication code. Please check your email and try again.", "OK");
            }
        }

        private async void SubmitCode()
        {
            if (string.IsNullOrEmpty(securityCode))
            {
                EditorUtility.DisplayDialog("Error", "Please enter the security code.", "OK");
                return;
            }

            bool success = await ModIOIntegration.Instance.SubmitSecurityCode(securityCode);
            
            if (success)
            {
                isAuthenticated = true;
                currentState = UploadState.Authenticated;
                EditorUtility.DisplayDialog("Success", "Authentication successful! You can now upload mods.", "OK");
            }
            else
            {
                EditorUtility.DisplayDialog("Error", "Invalid security code. Please try again.", "OK");
            }
        }

        private async void UploadMod()
        {
            if (selectedPackage == null)
            {
                EditorUtility.DisplayDialog("Error", "Please select a mod package to upload.", "OK");
                return;
            }

            if (!selectedPackage.ValidatePackage(out var errors))
            {
                EditorUtility.DisplayDialog("Validation Failed", 
                    $"Package validation failed:\n\n{string.Join("\n", errors)}", "OK");
                return;
            }

            string modDirectory = Path.Combine(Application.dataPath, "..", selectedPackage.BuildOutputPath, selectedPackage.PackageName);
            
            if (!Directory.Exists(modDirectory))
            {
                EditorUtility.DisplayDialog("Error", 
                    $"Build directory not found: {modDirectory}\n\nPlease build your asset bundles first.", "OK");
                return;
            }

            currentState = UploadState.Uploading;

            bool success = await ModIOIntegration.Instance.UploadModPackage(selectedPackage, modDirectory);
            
            if (success)
            {
                currentState = UploadState.Complete;
                EditorUtility.DisplayDialog("Success", 
                    $"Mod '{selectedPackage.PackageName}' has been successfully uploaded to mod.io!", "OK");
            }
            else
            {
                currentState = UploadState.Authenticated;
                EditorUtility.DisplayDialog("Upload Failed", 
                    "Failed to upload mod to mod.io. Check the console for details.", "OK");
            }
        }
    }
}
