using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class SettingsPanelBuilder : MonoBehaviour
{
    [Header("Configuration")]
    [SerializeField] private Vector2 panelSize = new Vector2(1200, 700);
    [SerializeField] private Color panelBackgroundColor = new Color(0.95f, 0.92f, 0.88f, 1f); // Beige clair
    [SerializeField] private Color darkBackgroundColor = new Color(0f, 0f, 0f, 0.7f);
    [SerializeField] private Color headerBackgroundColor = new Color(0.90f, 0.87f, 0.83f, 1f); // Beige moyen
    [SerializeField] private float headerHeight = 80f;
    
    private Canvas parentCanvas;
    private SettingsManager settingsManager;
    
    void Start()
    {
        parentCanvas = GetComponentInParent<Canvas>();
        if (parentCanvas == null)
        {
            Debug.LogError("[SettingsPanelBuilder] Canvas parent introuvable !");
            return;
        }
        
        BuildSettingsPanel();
    }
    
    void BuildSettingsPanel()
    {
        // 1. GameObject racine
        GameObject settingsPanel = new GameObject("SettingsPanel");
        settingsPanel.transform.SetParent(parentCanvas.transform, false);
        
        RectTransform panelRect = settingsPanel.AddComponent<RectTransform>();
        panelRect.anchorMin = Vector2.zero;
        panelRect.anchorMax = Vector2.one;
        panelRect.offsetMin = Vector2.zero;
        panelRect.offsetMax = Vector2.zero;
        
        CanvasGroup canvasGroup = settingsPanel.AddComponent<CanvasGroup>();
        canvasGroup.alpha = 1f;
        canvasGroup.interactable = true;
        canvasGroup.blocksRaycasts = true;
        
        Canvas settingsCanvas = settingsPanel.AddComponent<Canvas>();
        settingsCanvas.overrideSorting = true;
        settingsCanvas.sortingOrder = 500;
        
        settingsPanel.AddComponent<GraphicRaycaster>();
        
        // 2. Dark Background
        GameObject darkBg = CreateDarkBackground(settingsPanel.transform);
        
        // 3. Panel Container (rectangle central beige)
        GameObject panelContainer = CreatePanelContainer(settingsPanel.transform);
        
        // 4. Header avec onglets + croix
        GameObject headerBar = CreateHeaderWithTabs(panelContainer.transform, out GameObject closeButton);
        
        // 5. Content Area
        GameObject contentArea = CreateContentArea(panelContainer.transform);
        
        // 6. Créer les 4 onglets
        GameObject scoresTab = CreateScoresTab(contentArea.transform);
        GameObject classementTab = CreateClassementTab(contentArea.transform);
        GameObject quetesTab = CreateQuetesTab(contentArea.transform);
        GameObject parametresTab = CreateParametresTab(contentArea.transform);
        
        // 7. Ajouter SettingsManager
        settingsManager = settingsPanel.AddComponent<SettingsManager>();
        settingsManager.settingsPanel = settingsPanel;
        settingsManager.darkBackground = darkBg;
        settingsManager.closeButton = closeButton.GetComponent<Button>();
        settingsManager.tabs.Add(scoresTab.GetComponent<SettingsTab>());
        settingsManager.tabs.Add(classementTab.GetComponent<SettingsTab>());
        settingsManager.tabs.Add(quetesTab.GetComponent<SettingsTab>());
        settingsManager.tabs.Add(parametresTab.GetComponent<SettingsTab>());
        
        // Important : Les boutons d'onglets seront dans le header
        settingsManager.tabsContainer = headerBar.transform.Find("TabsContainer");
        settingsManager.contentContainer = contentArea.transform;
        
        // Désactiver au départ
        settingsPanel.SetActive(false);
        
        Debug.Log("[SettingsPanelBuilder] Panneau Settings créé avec succès !");
    }
    
    GameObject CreateDarkBackground(Transform parent)
    {
        GameObject darkBg = new GameObject("DarkBackground");
        darkBg.transform.SetParent(parent, false);
        
        RectTransform rect = darkBg.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = Vector2.zero;
        rect.offsetMax = Vector2.zero;
        
        Image image = darkBg.AddComponent<Image>();
        image.color = darkBackgroundColor;
        image.raycastTarget = true; // IMPORTANT : Bloquer les raycasts vers la map
        
        Button button = darkBg.AddComponent<Button>();
        button.transition = Selectable.Transition.None;
        
        return darkBg;
    }
    
 GameObject CreatePanelContainer(Transform parent)
{
    GameObject container = new GameObject("PanelContainer");
    container.transform.SetParent(parent, false);
    
    RectTransform rect = container.AddComponent<RectTransform>();
    
    // Utiliser les anchors pour 75% de largeur et hauteur adaptative
    rect.anchorMin = new Vector2(0.125f, 0.15f); // 12.5% de marge gauche (100-75)/2, 15% de marge bas
    rect.anchorMax = new Vector2(0.875f, 0.85f); // 87.5% pour centrer sur 75%, 85% en haut
    rect.pivot = new Vector2(0.5f, 0.5f);
    rect.offsetMin = Vector2.zero; // Pas d'offset supplémentaire
    rect.offsetMax = Vector2.zero;
    rect.anchoredPosition = Vector2.zero;
    
    Image image = container.AddComponent<Image>();
    image.color = panelBackgroundColor;
    image.raycastTarget = true; // IMPORTANT : Bloquer les raycasts vers la map
    
    return container;
}
    
    GameObject CreateHeaderWithTabs(Transform parent, out GameObject closeButtonOut)
    {
        GameObject header = new GameObject("HeaderBar");
        header.transform.SetParent(parent, false);
        
        RectTransform rect = header.AddComponent<RectTransform>();
        rect.anchorMin = new Vector2(0, 1);
        rect.anchorMax = new Vector2(1, 1);
        rect.pivot = new Vector2(0.5f, 1);
        rect.sizeDelta = new Vector2(0, headerHeight);
        rect.anchoredPosition = Vector2.zero;
        
        Image image = header.AddComponent<Image>();
        image.color = headerBackgroundColor;
        
        // Container pour les onglets (centré)
        GameObject tabsContainer = new GameObject("TabsContainer");
        tabsContainer.transform.SetParent(header.transform, false);
        
        RectTransform tabsRect = tabsContainer.AddComponent<RectTransform>();
        tabsRect.anchorMin = new Vector2(0, 0);
        tabsRect.anchorMax = new Vector2(1, 1);
        tabsRect.offsetMin = new Vector2(80, 10); // Marge gauche pour éviter la croix
        tabsRect.offsetMax = new Vector2(-80, -10); // Marge droite
        
        HorizontalLayoutGroup layout = tabsContainer.AddComponent<HorizontalLayoutGroup>();
        layout.spacing = 10;
        layout.childAlignment = TextAnchor.MiddleCenter;
        layout.childControlWidth = false;
        layout.childControlHeight = true;
        layout.childForceExpandWidth = false;
        layout.childForceExpandHeight = true;
        
        // Créer les 4 boutons d'onglets
        CreateTabButton(tabsContainer.transform, "SCORES", 0);
        CreateTabButton(tabsContainer.transform, "CLASSEMENT", 1);
        CreateTabButton(tabsContainer.transform, "QUÊTES", 2);
        CreateTabButton(tabsContainer.transform, "PARAMÈTRES", 3);
        
        // Bouton de fermeture (croix en haut à droite)
        GameObject closeButton = CreateCloseButtonInHeader(header.transform);
        closeButtonOut = closeButton;
        
        return header;
    }
    
    void CreateTabButton(Transform parent, string label, int index)
    {
        GameObject tabButton = new GameObject($"TabButton_{label}");
        tabButton.transform.SetParent(parent, false);
        
        RectTransform rect = tabButton.AddComponent<RectTransform>();
        rect.sizeDelta = new Vector2(180, 50);
        
        LayoutElement layoutElement = tabButton.AddComponent<LayoutElement>();
        layoutElement.preferredWidth = 180;
        layoutElement.preferredHeight = 50;
        
        Image image = tabButton.AddComponent<Image>();
        image.color = new Color(0.8f, 0.8f, 0.8f, 1f); // Gris inactif
        
        // Coins arrondis
        image.sprite = CreateRoundedSprite();
        image.type = Image.Type.Sliced;
        
        Button button = tabButton.AddComponent<Button>();
        button.targetGraphic = image;
        
        // Configurer les couleurs
        ColorBlock colors = button.colors;
        colors.normalColor = new Color(0.85f, 0.85f, 0.85f, 1f); // Gris clair
        colors.highlightedColor = new Color(0.75f, 0.6f, 0.85f, 1f); // Violet clair
        colors.pressedColor = new Color(0.6f, 0.4f, 0.8f, 1f); // Violet foncé
        colors.selectedColor = new Color(0.7f, 0.5f, 0.85f, 1f); // Violet actif
        button.colors = colors;
        
        // Ajouter le listener
        button.onClick.AddListener(() => {
            Debug.Log($"[TabButton] Clic sur {label}");
            if (SettingsManager.Instance != null)
            {
                SettingsManager.Instance.ShowTab(index);
            }
        });
        
        // Texte
        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(tabButton.transform, false);
        
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;
        
        TextMeshProUGUI text = textObj.AddComponent<TextMeshProUGUI>();
        text.text = label;
        text.fontSize = 18;
        text.fontStyle = FontStyles.Bold;
        text.alignment = TextAlignmentOptions.Center;
        text.color = new Color(0.3f, 0.3f, 0.4f, 1f); // Gris foncé
        
        // Note: Tag "TabButton" supprimé car non défini dans Unity
        // Les boutons sont identifiés par leur nom et composant Button
    }
    
    GameObject CreateCloseButtonInHeader(Transform parent)
    {
        GameObject closeBtn = new GameObject("CloseButton");
        closeBtn.transform.SetParent(parent, false);
        
        RectTransform rect = closeBtn.AddComponent<RectTransform>();
        rect.anchorMin = new Vector2(1, 0.5f);
        rect.anchorMax = new Vector2(1, 0.5f);
        rect.pivot = new Vector2(1, 0.5f);
        rect.sizeDelta = new Vector2(60, 60);
        rect.anchoredPosition = new Vector2(-10, 0);
        
        Image image = closeBtn.AddComponent<Image>();
        image.color = new Color(0.7f, 0.5f, 0.85f, 1f); // Violet
        
        // Rendre circulaire
        image.sprite = CreateCircleSprite();
        
        Button button = closeBtn.AddComponent<Button>();
        button.targetGraphic = image;
        
        ColorBlock colors = button.colors;
        colors.normalColor = new Color(0.7f, 0.5f, 0.85f, 1f);
        colors.highlightedColor = new Color(0.8f, 0.6f, 0.95f, 1f);
        colors.pressedColor = new Color(0.6f, 0.4f, 0.75f, 1f);
        button.colors = colors;
        
        button.onClick.AddListener(() => {
            Debug.Log("[CloseButton] Clic détecté !");
            if (SettingsManager.Instance != null)
            {
                SettingsManager.Instance.CloseSettings();
            }
        });
        
        // Icône X
        GameObject icon = CreateXIcon(closeBtn.transform);
        
        return closeBtn;
    }
    
    GameObject CreateXIcon(Transform parent)
    {
        GameObject xIcon = new GameObject("XIcon");
        xIcon.transform.SetParent(parent, false);
        
        RectTransform rect = xIcon.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = new Vector2(15, 15);
        rect.offsetMax = new Vector2(-15, -15);
        
        // Ligne 1
        GameObject line1 = new GameObject("Line1");
        line1.transform.SetParent(xIcon.transform, false);
        RectTransform line1Rect = line1.AddComponent<RectTransform>();
        line1Rect.anchorMin = new Vector2(0.5f, 0.5f);
        line1Rect.anchorMax = new Vector2(0.5f, 0.5f);
        line1Rect.pivot = new Vector2(0.5f, 0.5f);
        line1Rect.sizeDelta = new Vector2(35, 4);
        line1Rect.localEulerAngles = new Vector3(0, 0, 45);
        Image line1Image = line1.AddComponent<Image>();
        line1Image.color = Color.white;
        
        // Ligne 2
        GameObject line2 = new GameObject("Line2");
        line2.transform.SetParent(xIcon.transform, false);
        RectTransform line2Rect = line2.AddComponent<RectTransform>();
        line2Rect.anchorMin = new Vector2(0.5f, 0.5f);
        line2Rect.anchorMax = new Vector2(0.5f, 0.5f);
        line2Rect.pivot = new Vector2(0.5f, 0.5f);
        line2Rect.sizeDelta = new Vector2(35, 4);
        line2Rect.localEulerAngles = new Vector3(0, 0, -45);
        Image line2Image = line2.AddComponent<Image>();
        line2Image.color = Color.white;
        
        return xIcon;
    }
    
    GameObject CreateContentArea(Transform parent)
    {
        GameObject contentArea = new GameObject("ContentArea");
        contentArea.transform.SetParent(parent, false);
        
        RectTransform rect = contentArea.AddComponent<RectTransform>();
        rect.anchorMin = new Vector2(0, 0);
        rect.anchorMax = new Vector2(1, 1);
        rect.offsetMin = new Vector2(20, 20);
        rect.offsetMax = new Vector2(-20, -headerHeight - 10);
        
        return contentArea;
    }
    
    // Créer les 4 onglets (contenus vides pour l'instant)
    
    GameObject CreateScoresTab(Transform parent)
    {
        GameObject tab = new GameObject("ScoresTab");
        tab.transform.SetParent(parent, false);
        
        RectTransform rect = tab.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = Vector2.zero;
        rect.offsetMax = Vector2.zero;
        
        ScoresTab scoresTab = tab.AddComponent<ScoresTab>();
        
        // Texte temporaire
        GameObject textObj = new GameObject("TempText");
        textObj.transform.SetParent(tab.transform, false);
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;
        
        TextMeshProUGUI text = textObj.AddComponent<TextMeshProUGUI>();
        text.text = "ONGLET SCORES\n(À implémenter)";
        text.fontSize = 32;
        text.alignment = TextAlignmentOptions.Center;
        text.color = new Color(0.3f, 0.3f, 0.4f, 1f);
        
        return tab;
    }
    
    GameObject CreateClassementTab(Transform parent)
    {
        GameObject tab = new GameObject("ClassementTab");
        tab.transform.SetParent(parent, false);
        
        RectTransform rect = tab.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = Vector2.zero;
        rect.offsetMax = Vector2.zero;
        
        ClassementTab classementTab = tab.AddComponent<ClassementTab>();
        
        GameObject textObj = new GameObject("TempText");
        textObj.transform.SetParent(tab.transform, false);
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;
        
        TextMeshProUGUI text = textObj.AddComponent<TextMeshProUGUI>();
        text.text = "ONGLET CLASSEMENT\n(À implémenter)";
        text.fontSize = 32;
        text.alignment = TextAlignmentOptions.Center;
        text.color = new Color(0.3f, 0.3f, 0.4f, 1f);
        
        return tab;
    }
    
    GameObject CreateQuetesTab(Transform parent)
    {
        GameObject tab = new GameObject("QuetesTab");
        tab.transform.SetParent(parent, false);
        
        RectTransform rect = tab.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = Vector2.zero;
        rect.offsetMax = Vector2.zero;
        
        // Ajouter le composant QuetesTab qui gère toute l'interface
        QuetesTab quetesTab = tab.AddComponent<QuetesTab>();
        
        return tab;
    }
    
    GameObject CreateParametresTab(Transform parent)
    {
        GameObject tab = new GameObject("ParametresTab");
        tab.transform.SetParent(parent, false);
        
        RectTransform rect = tab.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = Vector2.zero;
        rect.offsetMax = Vector2.zero;
        
        VerticalLayoutGroup layout = tab.AddComponent<VerticalLayoutGroup>();
        layout.padding = new RectOffset(40, 40, 40, 40);
        layout.spacing = 30;
        layout.childAlignment = TextAnchor.UpperCenter;
        layout.childControlWidth = true;
        layout.childControlHeight = false;
        
        // Son
        GameObject soundSection = CreateSoundSection(tab.transform);
        
        // Bouton Quitter
        GameObject quitButton = CreateQuitButton(tab.transform);
        
        ParametresTab parametresTab = tab.AddComponent<ParametresTab>();
        parametresTab.soundToggle = soundSection.GetComponentInChildren<Toggle>();
        parametresTab.soundLabel = soundSection.GetComponentInChildren<TextMeshProUGUI>();
        parametresTab.quitButton = quitButton.GetComponent<Button>();
        
        return tab;
    }
    
    GameObject CreateSoundSection(Transform parent)
    {
        GameObject section = new GameObject("SoundSection");
        section.transform.SetParent(parent, false);
        
        RectTransform rect = section.AddComponent<RectTransform>();
        rect.sizeDelta = new Vector2(0, 120);
        
        LayoutElement layoutElement = section.AddComponent<LayoutElement>();
        layoutElement.preferredHeight = 120;
        
        VerticalLayoutGroup layout = section.AddComponent<VerticalLayoutGroup>();
        layout.spacing = 15;
        layout.childAlignment = TextAnchor.MiddleCenter;
        
        // Label
        GameObject label = new GameObject("SoundLabel");
        label.transform.SetParent(section.transform, false);
        TextMeshProUGUI labelText = label.AddComponent<TextMeshProUGUI>();
        labelText.text = "Son activé";
        labelText.fontSize = 28;
        labelText.alignment = TextAlignmentOptions.Center;
        labelText.color = new Color(0.3f, 0.3f, 0.4f, 1f);
        
        // Toggle
        GameObject toggle = CreateToggle(section.transform);
        
        return section;
    }
    
    GameObject CreateToggle(Transform parent)
    {
        GameObject toggleObj = new GameObject("SoundToggle");
        toggleObj.transform.SetParent(parent, false);
        
        RectTransform rect = toggleObj.AddComponent<RectTransform>();
        rect.sizeDelta = new Vector2(100, 50);
        
        Toggle toggle = toggleObj.AddComponent<Toggle>();
        toggle.isOn = true;
        
        // Background
        GameObject bg = new GameObject("Background");
        bg.transform.SetParent(toggleObj.transform, false);
        RectTransform bgRect = bg.AddComponent<RectTransform>();
        bgRect.anchorMin = Vector2.zero;
        bgRect.anchorMax = Vector2.one;
        bgRect.offsetMin = Vector2.zero;
        bgRect.offsetMax = Vector2.zero;
        Image bgImage = bg.AddComponent<Image>();
        bgImage.color = new Color(0.7f, 0.7f, 0.7f, 1f);
        
        // Checkmark
        GameObject check = new GameObject("Checkmark");
        check.transform.SetParent(bg.transform, false);
        RectTransform checkRect = check.AddComponent<RectTransform>();
        checkRect.anchorMin = Vector2.zero;
        checkRect.anchorMax = Vector2.one;
        checkRect.offsetMin = new Vector2(5, 5);
        checkRect.offsetMax = new Vector2(-5, -5);
        Image checkImage = check.AddComponent<Image>();
        checkImage.color = new Color(0.4f, 0.8f, 0.4f, 1f);
        
        toggle.targetGraphic = bgImage;
        toggle.graphic = checkImage;
        
        return toggleObj;
    }
    
    GameObject CreateQuitButton(Transform parent)
    {
        GameObject button = new GameObject("QuitButton");
        button.transform.SetParent(parent, false);
        
        RectTransform rect = button.AddComponent<RectTransform>();
        rect.sizeDelta = new Vector2(300, 60);
        
        LayoutElement layoutElement = button.AddComponent<LayoutElement>();
        layoutElement.preferredWidth = 300;
        layoutElement.preferredHeight = 60;
        
        Image image = button.AddComponent<Image>();
        image.color = new Color(0.8f, 0.3f, 0.3f, 1f);
        
        Button btn = button.AddComponent<Button>();
        btn.targetGraphic = image;
        
        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(button.transform, false);
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;
        
        TextMeshProUGUI text = textObj.AddComponent<TextMeshProUGUI>();
        text.text = "RETOUR AU MENU";
        text.fontSize = 22;
        text.fontStyle = FontStyles.Bold;
        text.alignment = TextAlignmentOptions.Center;
        text.color = Color.white;
        
        return button;
    }
    
    // Helpers pour créer des sprites
    
    Sprite CreateRoundedSprite()
    {
        Texture2D texture = new Texture2D(100, 100);
        Color[] pixels = new Color[100 * 100];
        
        for (int y = 0; y < 100; y++)
        {
            for (int x = 0; x < 100; x++)
            {
                pixels[y * 100 + x] = Color.white;
            }
        }
        
        texture.SetPixels(pixels);
        texture.Apply();
        
        return Sprite.Create(texture, new Rect(0, 0, 100, 100), new Vector2(0.5f, 0.5f), 100, 0, SpriteMeshType.FullRect, new Vector4(20, 20, 20, 20));
    }
    
    Sprite CreateCircleSprite()
    {
        int size = 128;
        Texture2D texture = new Texture2D(size, size);
        Color[] pixels = new Color[size * size];
        
        float center = size / 2f;
        float radius = size / 2f;
        
        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                float distance = Vector2.Distance(new Vector2(x, y), new Vector2(center, center));
                pixels[y * size + x] = distance <= radius ? Color.white : Color.clear;
            }
        }
        
        texture.SetPixels(pixels);
        texture.Apply();
        
        return Sprite.Create(texture, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f));
    }
}