using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

public class GameConfigLoader : MonoBehaviour
{
    [Serializable]
    public class GameConfigData
    {
        public string questionsUrl;
        public string dialogueBeforeUrl;
        public string dialogueSuccessUrl;
        public string dialogueFailUrl;
    }

    [Serializable]
    public class GameConfigWrapper
    {
        public GameConfigData gameConfig;
    }

    private void Start()
    {
        StartCoroutine(LoadAndProcessConfig());
    }

    private IEnumerator LoadAndProcessConfig()
    {
        // Attendre que GeneralConfigManager soit prêt
        while (GeneralConfigManager.Instance == null)
        {
            yield return null;
        }
        
        while (!GeneralConfigManager.Instance.IsConfigLoaded())
        {
            yield return null;
        }

        string configUrl = PlayerPrefs.GetString("GameConfigUrl");
        string phase = PlayerPrefs.GetString("GamePhase", "Before");
        string levelId = PlayerPrefs.GetString("CurrentLevelId");
        string levelType = PlayerPrefs.GetString("CurrentLevelType");

        DebugLogger.Log("=== DEBUG PLAYERPREFS ===", "GameConfigLoader");
        DebugLogger.Log($"ConfigUrl: '{configUrl}'", "GameConfigLoader");
        DebugLogger.Log($"Phase: '{phase}'", "GameConfigLoader");
        DebugLogger.Log($"LevelId: '{levelId}'", "GameConfigLoader");
        DebugLogger.Log($"LevelType: '{levelType}'", "GameConfigLoader");
        DebugLogger.Log("========================", "GameConfigLoader");

        DebugLogger.LogInfo($"URL: {configUrl}, Phase: {phase}", "GameConfigLoader");

        if (string.IsNullOrEmpty(configUrl))
        {
            DebugLogger.LogError("Aucune URL de config trouvée dans PlayerPrefs", "GameConfigLoader");
            yield break;
        }

        using (var www = UnityWebRequest.Get(configUrl))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                DebugLogger.LogError($"Erreur chargement config: {www.error}", "GameConfigLoader");
                yield break;
            }

            try
            {
                var wrapper = JsonUtility.FromJson<GameConfigWrapper>(www.downloadHandler.text);
                var config = wrapper.gameConfig;

                // Construire les URLs complètes via GeneralConfigManager
                string beforeUrl = string.IsNullOrEmpty(config.dialogueBeforeUrl) ? "" : 
                    GeneralConfigManager.Instance.GetDialogueUrl(config.dialogueBeforeUrl);
                string successUrl = string.IsNullOrEmpty(config.dialogueSuccessUrl) ? "" : 
                    GeneralConfigManager.Instance.GetDialogueUrl(config.dialogueSuccessUrl);
                string failUrl = string.IsNullOrEmpty(config.dialogueFailUrl) ? "" : 
                    GeneralConfigManager.Instance.GetDialogueUrl(config.dialogueFailUrl);
                string questionsUrl = string.IsNullOrEmpty(config.questionsUrl) ? "" : 
                    GeneralConfigManager.Instance.GetQuestionsUrl(config.questionsUrl);

                PlayerPrefs.SetString("DialogueBeforeUrl", beforeUrl);
                PlayerPrefs.SetString("DialogueSuccessUrl", successUrl);
                PlayerPrefs.SetString("DialogueFailUrl", failUrl);
                PlayerPrefs.SetString("QuestionsUrl", questionsUrl);

                DebugLogger.LogInfo($"Before URL: {beforeUrl}", "GameConfigLoader");
                DebugLogger.LogInfo($"Questions URL: {questionsUrl}", "GameConfigLoader");

                switch (phase)
                {
                    case "Before":
                        LaunchBeforeDialogue(beforeUrl);
                        break;
                    case "After":
                        string afterUrl = PlayerPrefs.GetString("NextDialogueUrl");
                        LaunchAfterDialogue(afterUrl);
                        break;
                }
            }
            catch (Exception e)
            {
                DebugLogger.LogError($"Erreur parsing config: {e.Message}", "GameConfigLoader");
                DebugLogger.LogError($"Stack trace: {e.StackTrace}", "GameConfigLoader");
            }
        }
    }

    private void LaunchBeforeDialogue(string beforeUrl)
    {
        if (string.IsNullOrEmpty(beforeUrl))
        {
            GoToGame();
            return;
        }

        ConfigureSubtitleManager(beforeUrl, () =>
        {
            GoToGame();
        });
    }

    private void LaunchAfterDialogue(string afterUrl)
    {
        if (string.IsNullOrEmpty(afterUrl))
        {
            ReturnToMap();
            return;
        }

        ConfigureSubtitleManager(afterUrl, () =>
        {
            ReturnToMap();
        });
    }

    private void GoToGame()
    {
        string levelType = PlayerPrefs.GetString("CurrentLevelType", "shooting");
        PlayerPrefs.SetString("GamePhase", "Game");

        if (levelType == "calculator")
        {
            SceneManager.LoadScene("calculator");
        }
        else
        {
            SceneManager.LoadScene("shooting");
        }
    }

    private void ReturnToMap()
    {
        LevelManager levelManager = FindFirstObjectByType<LevelManager>();
        if (levelManager != null)
        {
            levelManager.ReturnToMap();
        }
        else
        {
            PlayerPrefs.SetString("CurrentMapId", GeneralConfigManager.Instance != null ? 
                GeneralConfigManager.Instance.GetDefaultMapId() : "map_Q0J1");
            SceneManager.LoadScene("Map");
        }
    }

    private void ConfigureSubtitleManager(string dialogueUrl, System.Action onComplete)
    {
        SubtitleManager subtitleManager = FindFirstObjectByType<SubtitleManager>();
        if (subtitleManager != null)
        {
            subtitleManager.OnDialogueComplete = onComplete;

            DialogueConfig globalConfig = null;
            if (LevelManager.Instance != null)
            {
                globalConfig = LevelManager.Instance.GetDialogueConfig();
            }

            if (globalConfig != null)
            {
                DebugLogger.LogInfo("Application de la config dialogue globale", "GameConfigLoader");
                subtitleManager.ApplyDialogueConfig(globalConfig);
            }

            subtitleManager.LoadDialogueFromUrl(dialogueUrl);
        }
        else
        {
            DebugLogger.LogError("SubtitleManager non trouvé dans la scène Player", "GameConfigLoader");
            onComplete?.Invoke();
        }
    }
}