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

public class SettingsManager : MonoBehaviour
{
    public GameObject settingsPanel;
    public GameObject darkBackground;
    public Button closeButton;
    public Transform tabsContainer;
    public Transform contentContainer;
    public GameObject tabButtonPrefab;
    public List<SettingsTab> tabs = new List<SettingsTab>();
    public Color activeTabColor = new Color(1f, 1f, 1f, 1f);
    public Color inactiveTabColor = new Color(0.7f, 0.7f, 0.7f, 1f);
    
    private List<Button> tabButtons = new List<Button>();
    private static SettingsManager instance;
    private MapManager mapManager; // Référence au MapManager pour le désactiver
    
    public static SettingsManager Instance => instance;
    
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
            return;
        }
        
        if (settingsPanel != null)
        {
            settingsPanel.SetActive(false);
        }
        
        if (closeButton != null)
        {
            closeButton.onClick.RemoveAllListeners();
            closeButton.onClick.AddListener(CloseSettings);
        }
        
        if (darkBackground != null)
        {
            Button bgButton = darkBackground.GetComponent<Button>();
            if (bgButton != null)
            {
                bgButton.onClick.RemoveAllListeners();
                bgButton.onClick.AddListener(CloseSettings);
            }
        }
        
        // CORRECTION : Trouver le MapManager pour le désactiver quand le panneau est ouvert
        mapManager = FindFirstObjectByType<MapManager>();
        if (mapManager != null)
        {
            Debug.Log("[SettingsManager] MapManager trouvé - sera désactivé quand le panneau s'ouvre");
        }
        else
        {
            Debug.LogWarning("[SettingsManager] MapManager introuvable - normal si pas dans la scène Map");
        }
    }
    
    void Update()
    {
        if (settingsPanel != null && settingsPanel.activeSelf)
        {
            if (Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame)
            {
                CloseSettings();
            }
        }
    }
    
    public void OpenSettings()
    {
        if (settingsPanel != null)
        {
            settingsPanel.SetActive(true);
            CreateTabButtons();
            ShowTab(0);
            
            // CORRECTION : Désactiver le MapManager pour bloquer ses clics
            if (mapManager != null)
            {
                mapManager.enabled = false;
                Debug.Log("[SettingsManager] MapManager désactivé");
            }
        }
    }
    
    public void CloseSettings()
    {
        if (settingsPanel != null)
        {
            StartCoroutine(CloseWithFade());
        }
    }
    
    IEnumerator CloseWithFade()
    {
        CanvasGroup cg = settingsPanel.GetComponent<CanvasGroup>();
        if (cg == null)
        {
            cg = settingsPanel.AddComponent<CanvasGroup>();
        }
        
        float elapsed = 0f;
        float duration = 0.2f;
        
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            cg.alpha = Mathf.Lerp(1f, 0f, elapsed / duration);
            yield return null;
        }
        
        cg.alpha = 1f;
        settingsPanel.SetActive(false);
        
        // CORRECTION : Réactiver le MapManager quand le panneau se ferme
        if (mapManager != null)
        {
            mapManager.enabled = true;
            Debug.Log("[SettingsManager] MapManager réactivé");
        }
    }
    
    void CreateTabButtons()
    {
        // Les boutons sont déjà créés par SettingsPanelBuilder
        // Cette méthode n'est plus nécessaire mais on la garde pour compatibilité
        if (tabButtons.Count > 0) return;
        
        // Si tabsContainer est null, sortir
        if (tabsContainer == null)
        {
            Debug.LogWarning("[SettingsManager] tabsContainer est null, impossible de créer les boutons");
            return;
        }
        
        // Récupérer les boutons existants créés par SettingsPanelBuilder
        foreach (Transform child in tabsContainer)
        {
            Button button = child.GetComponent<Button>();
            if (button != null)
            {
                tabButtons.Add(button);
            }
        }
        
        Debug.Log($"[SettingsManager] {tabButtons.Count} boutons d'onglets trouvés");
    }
    

    
    public void RegisterTab(SettingsTab tab)
    {
        if (!tabs.Contains(tab))
        {
            tabs.Add(tab);
        }
    }


    public void ShowTab(int index)
{
    if (index < 0 || index >= tabs.Count) return;
    
    Debug.Log($"[SettingsManager] ShowTab({index})");
    
    for (int i = 0; i < tabs.Count; i++)
    {
        tabs[i].gameObject.SetActive(i == index);
    }
    
    // Mettre à jour les couleurs des boutons d'onglets
    UpdateTabButtonColors(index);
}

void UpdateTabButtonColors(int activeIndex)
{
    if (tabsContainer == null) return;
    
    int buttonIndex = 0;
    foreach (Transform child in tabsContainer)
    {
        Button button = child.GetComponent<Button>();
        Image image = child.GetComponent<Image>();
        
        if (button != null && image != null)
        {
            if (buttonIndex == activeIndex)
            {
                image.color = new Color(0.7f, 0.5f, 0.85f, 1f); // Violet actif
            }
            else
            {
                image.color = new Color(0.85f, 0.85f, 0.85f, 1f); // Gris inactif
            }
            buttonIndex++;
        }
    }
}
}