using UnityEngine;
using UnityEngine.UI;
using TMPro;

#if UNITY_EDITOR
using UnityEditor;
#endif

/// <summary>
/// Script helper pour créer automatiquement un écran de chargement complet
/// Usage : Menu Unity → Tools → Create Loading Screen
/// </summary>
public class LoadingScreenSetupHelper : MonoBehaviour
{
    [Header("Personnalisation")]
    [Tooltip("Couleur du fond (si pas d'image)")]
    public Color backgroundColor = Color.black;
    
    [Tooltip("Image de fond personnalisée (optionnel)")]
    public Sprite backgroundImage;
    
    [Tooltip("Icône de chargement qui tourne (optionnel)")]
    public Sprite loadingIcon;
    
    [Tooltip("Logo du jeu à afficher en haut (optionnel)")]
    public Sprite gameLogo;
    
    [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...";
    
    [Header("Style")]
    [Tooltip("Taille de la police du texte")]
    public float fontSize = 42f;
    
    [Tooltip("Couleur du texte")]
    public Color textColor = Color.white;
    
    [Tooltip("Police personnalisée (optionnel)")]
    public TMP_FontAsset customFont;
    
#if UNITY_EDITOR
    [ContextMenu("Créer l'Écran de Chargement")]
    public void CreateLoadingScreen()
    {
        // Créer le Canvas principal
        GameObject canvasObj = new GameObject("LoadingScreenCanvas");
        Canvas canvas = canvasObj.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        canvas.sortingOrder = 9999;
        
        CanvasScaler scaler = canvasObj.AddComponent<CanvasScaler>();
        scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        scaler.referenceResolution = new Vector2(1920, 1080);
        scaler.matchWidthOrHeight = 0.5f;
        
        canvasObj.AddComponent<GraphicRaycaster>();
        
        // Créer le fond
        GameObject bgObj = new GameObject("BlackBackground");
        bgObj.transform.SetParent(canvasObj.transform, false);
        
        RectTransform bgRect = bgObj.AddComponent<RectTransform>();
        bgRect.anchorMin = Vector2.zero;
        bgRect.anchorMax = Vector2.one;
        bgRect.sizeDelta = Vector2.zero;
        bgRect.anchoredPosition = Vector2.zero;
        
        Image bgImage = bgObj.AddComponent<Image>();
        if (backgroundImage != null)
        {
            bgImage.sprite = backgroundImage;
            bgImage.color = Color.white;
        }
        else
        {
            bgImage.color = backgroundColor;
        }
        
        // Créer le conteneur central
        GameObject contentObj = new GameObject("LoadingContent");
        contentObj.transform.SetParent(canvasObj.transform, false);
        
        RectTransform contentRect = contentObj.AddComponent<RectTransform>();
        contentRect.anchorMin = new Vector2(0.5f, 0.5f);
        contentRect.anchorMax = new Vector2(0.5f, 0.5f);
        contentRect.sizeDelta = new Vector2(400, 200);
        contentRect.anchoredPosition = Vector2.zero;
        
        // Créer l'icône de chargement (si fournie)
        GameObject iconObj = null;
        if (loadingIcon != null)
        {
            iconObj = new GameObject("LoadingIcon");
            iconObj.transform.SetParent(contentObj.transform, false);
            
            RectTransform iconRect = iconObj.AddComponent<RectTransform>();
            iconRect.anchorMin = new Vector2(0.5f, 0.5f);
            iconRect.anchorMax = new Vector2(0.5f, 0.5f);
            iconRect.sizeDelta = new Vector2(64, 64);
            iconRect.anchoredPosition = new Vector2(0, 40);
            
            Image iconImage = iconObj.AddComponent<Image>();
            iconImage.sprite = loadingIcon;
            iconImage.color = textColor;
        }
        
        // Créer le texte de chargement
        GameObject textObj = new GameObject("LoadingText");
        textObj.transform.SetParent(contentObj.transform, false);
        
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = new Vector2(0.5f, 0.5f);
        textRect.anchorMax = new Vector2(0.5f, 0.5f);
        textRect.sizeDelta = new Vector2(600, 100);
        textRect.anchoredPosition = new Vector2(0, iconObj != null ? -40 : 0);
        
        TextMeshProUGUI text = textObj.AddComponent<TextMeshProUGUI>();
        text.text = defaultMessage;
        text.fontSize = fontSize;
        text.color = textColor;
        text.alignment = TextAlignmentOptions.Center;
        text.textWrappingMode = TMPro.TextWrappingModes.Normal;
        
        if (customFont != null)
        {
            text.font = customFont;
        }
        
        // Créer le logo (si fourni)
        if (gameLogo != null)
        {
            GameObject logoObj = new GameObject("GameLogo");
            logoObj.transform.SetParent(canvasObj.transform, false);
            
            RectTransform logoRect = logoObj.AddComponent<RectTransform>();
            logoRect.anchorMin = new Vector2(0.5f, 1f);
            logoRect.anchorMax = new Vector2(0.5f, 1f);
            logoRect.sizeDelta = new Vector2(300, 150);
            logoRect.anchoredPosition = new Vector2(0, -100);
            
            Image logoImage = logoObj.AddComponent<Image>();
            logoImage.sprite = gameLogo;
            logoImage.preserveAspect = true;
        }
        
        // Ajouter le LoadingScreenManager
        LoadingScreenManager manager = canvasObj.AddComponent<LoadingScreenManager>();
        
        // Assigner les références
        var managerSO = new SerializedObject(manager);
        managerSO.FindProperty("loadingCanvas").objectReferenceValue = canvas;
        managerSO.FindProperty("backgroundImage").objectReferenceValue = bgImage;
        managerSO.FindProperty("loadingText").objectReferenceValue = text;
        if (iconObj != null)
        {
            managerSO.FindProperty("loadingIcon").objectReferenceValue = iconObj.GetComponent<Image>();
        }
        
        managerSO.FindProperty("defaultMessage").stringValue = defaultMessage;
        managerSO.FindProperty("gameLoadingMessage").stringValue = gameLoadingMessage;
        managerSO.FindProperty("mapLoadingMessage").stringValue = mapLoadingMessage;
        managerSO.FindProperty("videoLoadingMessage").stringValue = videoLoadingMessage;
        
        managerSO.ApplyModifiedProperties();
        
        // Désactiver le canvas par défaut
        canvasObj.SetActive(false);
        
        // Marquer comme DontDestroyOnLoad
        DontDestroyOnLoad(canvasObj);
        
        Debug.Log("✅ Écran de chargement créé avec succès !");
        Debug.Log("Le canvas est désactivé par défaut - il s'activera automatiquement pendant les chargements");
        
        // Sélectionner le canvas créé
        Selection.activeGameObject = canvasObj;
    }
#endif
}

#if UNITY_EDITOR
[CustomEditor(typeof(LoadingScreenSetupHelper))]
public class LoadingScreenSetupHelperEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        
        EditorGUILayout.Space(10);
        EditorGUILayout.HelpBox(
            "Ce script aide à créer un écran de chargement complet.\n\n" +
            "1. Configurez les options ci-dessus\n" +
            "2. Cliquez sur 'Créer l'Écran de Chargement'\n" +
            "3. Un canvas complet sera créé automatiquement !",
            MessageType.Info
        );
        
        EditorGUILayout.Space(5);
        
        LoadingScreenSetupHelper helper = (LoadingScreenSetupHelper)target;
        
        if (GUILayout.Button("🎨 Créer l'Écran de Chargement", GUILayout.Height(40)))
        {
            helper.CreateLoadingScreen();
        }
    }
}
#endif

