using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using TMPro;
using System.Text;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Onglet Debug qui affiche toutes les variables utilisateur stockées
/// </summary>
public class DebugTab : SettingsTab
{
    public Transform contentContainer;
    private TextMeshProUGUI debugText;
    private List<Quest> cachedQuests = new List<Quest>();
    private bool isLoadingQuests = false;
    
    protected override void Awake()
    {
        base.Awake();
        tabName = "DEBUG";
        tabOrder = 4;
    }
    
    protected override void OnEnable()
    {
        base.OnEnable();
        // Charger les données des quêtes puis afficher
        StartCoroutine(LoadAndUpdateDebugInfo());
    }
    
    IEnumerator LoadAndUpdateDebugInfo()
    {
        // D'abord essayer MainSceneManager
        MainSceneManager mainSceneManager = FindFirstObjectByType<MainSceneManager>();
        
        if (mainSceneManager != null)
        {
            // MainSceneManager disponible, utiliser ses données
            cachedQuests.Clear();
            var sceneConfigField = mainSceneManager.GetType().GetField("sceneConfig", 
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            
            if (sceneConfigField != null)
            {
                var sceneConfig = sceneConfigField.GetValue(mainSceneManager) as MainSceneConfig;
                if (sceneConfig?.quests != null)
                {
                    cachedQuests = sceneConfig.quests;
                }
            }
            UpdateDebugInfo();
        }
        else
        {
            // Pas de MainSceneManager, charger depuis l'API
            if (!isLoadingQuests)
            {
                isLoadingQuests = true;
                yield return StartCoroutine(LoadQuestsFromApi());
                isLoadingQuests = false;
            }
            UpdateDebugInfo();
        }
    }
    
    IEnumerator LoadQuestsFromApi()
    {
        cachedQuests.Clear();
        
        GeneralConfigManager configManager = GeneralConfigManager.Instance;
        if (configManager == null)
        {
            yield break;
        }
        
        string apiUrl = configManager.GetMainSceneConfigApiUrl();
        if (string.IsNullOrEmpty(apiUrl))
        {
            yield break;
        }
        
        string token = UserDataManager.Instance != null ? UserDataManager.Instance.token : "";
        
        using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
        {
            if (!string.IsNullOrEmpty(token))
            {
                request.SetRequestHeader("Authorization", $"Bearer {token}");
            }
            
            yield return request.SendWebRequest();
            
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogWarning($"[DebugTab] Erreur API: {request.error}");
                yield break;
            }
            
            string jsonResponse = request.downloadHandler.text;
            
            try
            {
                ApiMainSceneResponse response = JsonUtility.FromJson<ApiMainSceneResponse>(jsonResponse);
                
                if (response != null && response.status == "success" && response.data?.quests != null)
                {
                    foreach (var apiQuest in response.data.quests)
                    {
                        Quest quest = new Quest
                        {
                            id = apiQuest.id,
                            title = apiQuest.title,
                            has_access = apiQuest.has_access,
                            user = apiQuest.user
                        };
                        cachedQuests.Add(quest);
                    }
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError($"[DebugTab] Exception JSON: {e.Message}");
            }
        }
    }
    
    void UpdateDebugInfo()
    {
        if (contentContainer == null)
        {
            Debug.LogError("[DebugTab] ❌ contentContainer est NULL !");
            return;
        }
        
        // Nettoyer l'ancien contenu
        foreach (Transform child in contentContainer)
        {
            Destroy(child.gameObject);
        }
        debugText = null;
        
        // Construire le texte avec toutes les informations utilisateur
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("═══════════════════════════════════════════════════════════");
        sb.AppendLine("<size=24><b>INFORMATIONS DE DEBUG</b></size>");
        sb.AppendLine("═══════════════════════════════════════════════════════════");
        sb.AppendLine();
        
        if (UserDataManager.Instance != null)
        {
            if (UserDataManager.Instance.IsLoggedIn())
            {
                sb.AppendLine("<b><size=22>UTILISATEUR CONNECTÉ</size></b>");
                sb.AppendLine();
                sb.AppendLine($"<b>User ID:</b> {UserDataManager.Instance.userId}");
                sb.AppendLine($"<b>Email:</b> {UserDataManager.Instance.email}");
                sb.AppendLine();
                sb.AppendLine($"<b>Temps de jeu:</b> {UserDataManager.Instance.FormatPlayTime(UserDataManager.Instance.playTime)}");
                sb.AppendLine();
                sb.AppendLine("───────────────────────────────────────────────────────────");
                sb.AppendLine();
                
                // Récupérer les quêtes depuis MainSceneManager
                AppendQuestsInfo(sb);
            }
            else
            {
                sb.AppendLine("<size=22><b>UTILISATEUR NON CONNECTÉ</b></size>");
                sb.AppendLine();
                sb.AppendLine("<i>Connectez-vous pour voir vos données de progression.</i>");
                sb.AppendLine();
                sb.AppendLine($"<b>Temps de jeu:</b> {UserDataManager.Instance.FormatPlayTime(UserDataManager.Instance.playTime)}");
            }
        }
        else
        {
            Debug.LogWarning("[DebugTab] UserDataManager.Instance est NULL !");
            sb.AppendLine("<size=22><b>ERREUR SYSTÈME</b></size>");
            sb.AppendLine();
            sb.AppendLine("<color=red>UserDataManager non initialisé</color>");
            sb.AppendLine();
            sb.AppendLine("Veuillez redémarrer le jeu.");
        }
        
        sb.AppendLine();
        sb.AppendLine("═══════════════════════════════════════════════════════════");
        
        string finalText = sb.ToString();
        
        // Créer un simple TextMeshProUGUI dans le contentContainer
        GameObject textObj = new GameObject("DebugText");
        textObj.transform.SetParent(contentContainer, false);
        
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;
        
        debugText = textObj.AddComponent<TextMeshProUGUI>();
        
        // CRITIQUE : Charger un font asset pour TextMeshPro
        TMP_FontAsset font = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
        if (font == null)
        {
            // Fallback : utiliser le premier font disponible
            TMP_FontAsset[] fonts = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
            if (fonts.Length > 0) font = fonts[0];
        }
        if (font != null) debugText.font = font;
        
        debugText.text = finalText;
        debugText.fontSize = 20;
        debugText.alignment = TextAlignmentOptions.TopLeft;
        debugText.color = new Color(0.1f, 0.1f, 0.1f, 1f);
        debugText.textWrappingMode = TMPro.TextWrappingModes.Normal;
        debugText.overflowMode = TMPro.TextOverflowModes.Overflow;
    }
    
    
    void AppendQuestsInfo(StringBuilder sb)
    {
        sb.AppendLine("<b><size=22>QUÊTES EN COURS</size></b>");
        sb.AppendLine();
        
        if (cachedQuests != null && cachedQuests.Count > 0)
        {
            int inProgressCount = 0;
            
            foreach (var quest in cachedQuests)
            {
                if (quest.user != null)
                {
                    foreach (var userProgress in quest.user)
                    {
                        // Afficher seulement si completion > 0
                        if (userProgress.completion > 0)
                        {
                            inProgressCount++;
                            
                            sb.AppendLine($"<b>{quest.title}</b>");
                            sb.AppendLine($"  • <b>Difficulté:</b> <color=#6495ED>{userProgress.difficulty}</color>");
                            sb.AppendLine($"  • <b>Completion:</b> {userProgress.completion}%");
                            sb.AppendLine($"  • <b>Score:</b> {userProgress.score}");
                            sb.AppendLine($"  • <b>Badge:</b> {(string.IsNullOrEmpty(userProgress.badge) ? "Aucun" : userProgress.badge)}");
                            sb.AppendLine($"  • <b>Dernier jeu complété:</b> {(userProgress.last_completed_game > 0 ? userProgress.last_completed_game.ToString() : "Aucun")}");
                            sb.AppendLine();
                        }
                    }
                }
            }
            
            if (inProgressCount == 0)
            {
                sb.AppendLine("<i>Aucune quête en cours (completion > 0)</i>");
                sb.AppendLine();
            }
        }
        else
        {
            sb.AppendLine("<i>Aucune donnée de quête disponible</i>");
            sb.AppendLine();
        }
    }
    
}
