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

public class LoadingScreenManager : MonoBehaviour
{
    [Header("Loading Screen UI")]
    public Canvas loadingCanvas;
    public Image backgroundImage;
    public TextMeshProUGUI loadingText;
    public Image loadingIcon;
    
    [Header("Animation Settings")]
    public float dotAnimationSpeed = 0.5f;
    public float iconRotationSpeed = 90f;
    public float fadeInDuration = 0.3f;
    public float fadeOutDuration = 0.3f;
    
    [Header("Messages")]
    public string defaultMessage = "Chargement en cours";
    public string gameLoadingMessage = "Chargement du jeu...";
    public string mapLoadingMessage = "Chargement de la carte...";
    public string videoLoadingMessage = "Chargement de la vidéo...";
    public string assetsLoadingMessage = "Chargement des ressources...";
    
    private static LoadingScreenManager instance;
    private Coroutine loadingAnimationCoroutine;
    private Coroutine fadeCoroutine;
    private bool isLoading = false;
    private Queue<string> loadingQueue = new Queue<string>();
    
    public static LoadingScreenManager Instance => instance;
    public bool IsLoading => isLoading;
    
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
            
            // Assigner automatiquement si pas déjà fait
            if (loadingCanvas == null)
            {
                loadingCanvas = GetComponent<Canvas>();
            }
            
            SetupLoadingScreen();
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void SetupLoadingScreen()
    {
        // Vérifier que tous les composants existent
        if (loadingCanvas != null)
        {
            loadingCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
            loadingCanvas.sortingOrder = 9999; // Très haut pour être au-dessus de tout
        }
        
        // Vérifier backgroundImage avant utilisation
        if (backgroundImage != null)
        {
            backgroundImage.color = Color.black;
        }
        
        // Si pas de background image, créer un écran noir simple
        if (backgroundImage == null && loadingCanvas != null)
        {
            CreateSimpleBlackScreen();
        }
        
        // Masquer par défaut
        if (loadingCanvas != null)
        {
            loadingCanvas.gameObject.SetActive(false);
        }
    }
    
    /// <summary>
    /// Crée un écran noir simple si aucun background n'est configuré
    /// </summary>
    void CreateSimpleBlackScreen()
    {
        GameObject bgObj = new GameObject("BlackScreen");
        bgObj.transform.SetParent(loadingCanvas.transform, false);
        
        RectTransform rectTransform = bgObj.AddComponent<RectTransform>();
        rectTransform.anchorMin = Vector2.zero;
        rectTransform.anchorMax = Vector2.one;
        rectTransform.sizeDelta = Vector2.zero;
        rectTransform.anchoredPosition = Vector2.zero;
        
        backgroundImage = bgObj.AddComponent<Image>();
        backgroundImage.color = Color.black;
        
        Debug.Log("[LoadingScreenManager] Écran noir simple créé automatiquement");
    }
    
    /// <summary>
    /// Affiche l'écran de chargement avec un message spécifique
    /// </summary>
    public void ShowLoading(string message = null, bool immediate = false)
    {
        if (string.IsNullOrEmpty(message))
            message = defaultMessage;
            
        loadingQueue.Enqueue(message);
        
        if (!isLoading)
        {
            if (immediate)
            {
                if (loadingCanvas != null)
                {
                    loadingCanvas.gameObject.SetActive(true);
                }
                if (loadingText != null)
                {
                    loadingText.text = message;
                }
                isLoading = true;
                StartLoadingAnimation();
            }
            else
            {
                StartCoroutine(ShowLoadingWithFade(true, message));
            }
        }
        else
        {
            // Si déjà en cours de chargement, juste changer le message
            SetLoadingMessage(message);
        }
    }
    
    /// <summary>
    /// Cache l'écran de chargement
    /// </summary>
    public void HideLoading(bool immediate = false)
    {
        if (loadingQueue.Count > 0)
        {
            loadingQueue.Dequeue();
        }
        
        if (loadingQueue.Count == 0)
        {
            if (immediate)
            {
                if (loadingCanvas != null)
                {
                    loadingCanvas.gameObject.SetActive(false);
                }
                isLoading = false;
                StopLoadingAnimation();
            }
            else
            {
                StartCoroutine(ShowLoadingWithFade(false));
            }
        }
    }
    
    /// <summary>
    /// Méthodes de convenance pour différents types de chargement
    /// </summary>
    public void ShowGameLoading() => ShowLoading(gameLoadingMessage);
    public void ShowMapLoading() => ShowLoading(mapLoadingMessage);
    public void ShowVideoLoading() => ShowLoading(videoLoadingMessage);
    public void ShowAssetsLoading() => ShowLoading(assetsLoadingMessage);
    
    /// <summary>
    /// Cache l'écran de chargement avec un délai
    /// </summary>
    public void HideLoadingAfterDelay(float delay)
    {
        StartCoroutine(HideLoadingAfterDelayCoroutine(delay));
    }
    
    private IEnumerator HideLoadingAfterDelayCoroutine(float delay)
    {
        yield return new WaitForSeconds(delay);
        HideLoading();
    }
    
    private IEnumerator ShowLoadingWithFade(bool show, string message = null)
    {
        if (fadeCoroutine != null)
        {
            StopCoroutine(fadeCoroutine);
        }
        
        fadeCoroutine = StartCoroutine(FadeLoadingScreen(show, message));
        yield return fadeCoroutine;
    }
    
    private IEnumerator FadeLoadingScreen(bool show, string message = null)
    {
        float duration = show ? fadeInDuration : fadeOutDuration;
        float elapsedTime = 0f;
        
        if (show && !string.IsNullOrEmpty(message))
        {
            SetLoadingMessage(message);
        }
        
        CanvasGroup canvasGroup = loadingCanvas.GetComponent<CanvasGroup>();
        if (canvasGroup == null)
        {
            canvasGroup = loadingCanvas.gameObject.AddComponent<CanvasGroup>();
        }
        
        float startAlpha = show ? 0f : 1f;
        float targetAlpha = show ? 1f : 0f;
        
        canvasGroup.alpha = startAlpha;
        
        while (elapsedTime < duration)
        {
            elapsedTime += Time.deltaTime;
            float alpha = Mathf.Lerp(startAlpha, targetAlpha, elapsedTime / duration);
            canvasGroup.alpha = alpha;
            yield return null;
        }
        
        canvasGroup.alpha = targetAlpha;
        
        if (show)
        {
            isLoading = true;
            StartLoadingAnimation();
        }
        else
        {
            isLoading = false;
            StopLoadingAnimation();
        }
        
        fadeCoroutine = null;
    }
    
    /// <summary>
    /// Méthode legacy - utilisez ShowLoading() et HideLoading() à la place
    /// </summary>
    [System.Obsolete("Utilisez ShowLoading() et HideLoading() à la place")]
    public void ShowLoadingScreen(bool show, string message = "Chargement en cours")
    {
        Debug.Log($"ShowLoadingScreen appelé avec show={show}, message={message}");
        
        if (loadingCanvas != null)
        {
            loadingCanvas.gameObject.SetActive(show);
            Debug.Log($"Canvas SetActive({show}) - Canvas actif: {loadingCanvas.gameObject.activeInHierarchy}");
        }
        else
        {
            Debug.LogError("loadingCanvas est null dans ShowLoadingScreen!");
            return;
        }
        
        if (show)
        {
            if (loadingText != null)
            {
                loadingText.text = message;
            }
            isLoading = true;
            StartLoadingAnimation();
        }
        else
        {
            isLoading = false;
            StopLoadingAnimation();
        }
    }
    
    void StartLoadingAnimation()
    {
        if (loadingAnimationCoroutine != null)
        {
            StopCoroutine(loadingAnimationCoroutine);
        }
        
        if (loadingText != null)
        {
            loadingAnimationCoroutine = StartCoroutine(LoadingAnimation());
        }
    }
    
    void StopLoadingAnimation()
    {
        if (loadingAnimationCoroutine != null)
        {
            StopCoroutine(loadingAnimationCoroutine);
            loadingAnimationCoroutine = null;
        }
    }
    
    IEnumerator LoadingAnimation()
    {
        if (loadingText == null) yield break;
        
        string baseText = loadingText.text.Replace("...", "");
        int dotCount = 0;
        
        while (true)
        {
            // Animation des points
            string dots = new string('.', dotCount + 1);
            if (loadingText != null)
            {
                loadingText.text = baseText + dots;
            }
            
            dotCount = (dotCount + 1) % 3;
            
            // Rotation de l'icône si présente
            if (loadingIcon != null)
            {
                loadingIcon.transform.Rotate(0, 0, -iconRotationSpeed * Time.deltaTime);
            }
            
            yield return new WaitForSeconds(dotAnimationSpeed);
        }
    }
    
    public void SetLoadingMessage(string message)
    {
        if (loadingText != null)
        {
            loadingText.text = message;
        }
        else
        {
            Debug.LogWarning("LoadingText est null - impossible de définir le message");
        }
    }
    
    /// <summary>
    /// Force l'affichage immédiat de l'écran de chargement (pour les cas critiques)
    /// </summary>
    public void ForceShowLoading(string message = null)
    {
        if (string.IsNullOrEmpty(message))
            message = defaultMessage;
            
        if (loadingCanvas != null)
        {
            loadingCanvas.gameObject.SetActive(true);
        }
        if (loadingText != null)
        {
            loadingText.text = message;
        }
        isLoading = true;
        StartLoadingAnimation();
    }
    
    /// <summary>
    /// Force la disparition immédiate de l'écran de chargement
    /// </summary>
    public void ForceHideLoading()
    {
        if (loadingCanvas != null)
        {
            loadingCanvas.gameObject.SetActive(false);
        }
        isLoading = false;
        StopLoadingAnimation();
        loadingQueue.Clear();
    }
}