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

public class TrousDropdown : MonoBehaviour
{
    [Header("UI References")]
    public Button dropdownButton;
    public TextMeshProUGUI buttonText;
    public GameObject dropdownPanel;
    public Transform optionsContainer;
    public GameObject optionPrefab;
    
    private TrousHole hole;
    private TrousDropdownConfig config;
    private Action<TrousDropdown, string> onValueChanged;
    private string selectedValue = "";
    private bool isOpen = false;
    private bool isCorrect = false;
    
    public void Initialize(TrousHole holeData, TrousDropdownConfig dropdownConfig, Action<TrousDropdown, string> callback)
    {
        hole = holeData;
        config = dropdownConfig;
        onValueChanged = callback;
        
        SetupDropdown();
        CreateOptions();
    }
    
    private void SetupDropdown()
    {
        // Ajouter une Image au bouton principal si elle n'existe pas
        Image buttonImage = GetComponent<Image>();
        if (buttonImage == null)
        {
            buttonImage = gameObject.AddComponent<Image>();
            buttonImage.color = ParseColor(config.backgroundColor);
        }
        
        // Configurer le bouton principal
        if (dropdownButton == null)
        {
            dropdownButton = GetComponent<Button>();
            if (dropdownButton == null)
            {
                dropdownButton = gameObject.AddComponent<Button>();
            }
        }
        
        dropdownButton.targetGraphic = buttonImage;
        dropdownButton.onClick.AddListener(ToggleDropdown);
        
        // Configurer le texte du bouton
        if (buttonText == null)
        {
            buttonText = GetComponentInChildren<TextMeshProUGUI>();
            if (buttonText == null)
            {
                GameObject textObj = new GameObject("ButtonText");
                textObj.transform.SetParent(transform);
                
                RectTransform textRect = textObj.AddComponent<RectTransform>();
                textRect.anchorMin = Vector2.zero;
                textRect.anchorMax = Vector2.one;
                textRect.sizeDelta = Vector2.zero;
                textRect.anchoredPosition = Vector2.zero;
                
                buttonText = textObj.AddComponent<TextMeshProUGUI>();
            }
        }
        
        buttonText.text = "Choisir...";
        buttonText.fontSize = config.fontSize;
        buttonText.color = ParseColor(config.fontColor);
        buttonText.alignment = TextAlignmentOptions.Center;
        buttonText.verticalAlignment = VerticalAlignmentOptions.Middle;
        
        // Configurer le panneau de dropdown
        if (dropdownPanel == null)
        {
            dropdownPanel = new GameObject("DropdownPanel");
            dropdownPanel.transform.SetParent(transform);
            
            RectTransform panelRect = dropdownPanel.AddComponent<RectTransform>();
            panelRect.anchoredPosition = Vector2.zero;
            panelRect.sizeDelta = new Vector2(200, config.maxVisibleItems * config.itemHeight);
            
            Image panelImage = dropdownPanel.AddComponent<Image>();
            panelImage.color = ParseColor(config.backgroundColor);
            
            // Ajouter une bordure
            Outline outline = dropdownPanel.AddComponent<Outline>();
            outline.effectColor = ParseColor(config.borderColor);
            outline.effectDistance = new Vector2(config.borderWidth, config.borderWidth);
        }
        
        dropdownPanel.SetActive(false);
        
        // Configurer le conteneur des options
        if (optionsContainer == null)
        {
            optionsContainer = dropdownPanel.transform;
        }
    }
    
    private void CreateOptions()
    {
        if (hole.options == null) return;
        
        foreach (string option in hole.options)
        {
            CreateOption(option);
        }
    }
    
    private void CreateOption(string optionText)
    {
        GameObject optionObj = new GameObject($"Option_{optionText}");
        optionObj.transform.SetParent(optionsContainer);
        
        // Ajouter RectTransform
        RectTransform optionRect = optionObj.AddComponent<RectTransform>();
        optionRect.anchoredPosition = Vector2.zero;
        optionRect.sizeDelta = new Vector2(200, config.itemHeight);
        
        // Ajouter Button
        Button optionButton = optionObj.AddComponent<Button>();
        optionButton.onClick.AddListener(() => SelectOption(optionText));
        
        // Ajouter Image pour le fond
        Image optionImage = optionObj.AddComponent<Image>();
        optionImage.color = Color.clear;
        
        // Créer un GameObject enfant pour le texte (car Unity n'autorise qu'un seul Graphic par GameObject)
        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(optionObj.transform);
        
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.sizeDelta = Vector2.zero;
        textRect.anchoredPosition = Vector2.zero;
        
        // Ajouter TextMeshProUGUI au GameObject enfant
        TextMeshProUGUI optionTextComponent = textObj.AddComponent<TextMeshProUGUI>();
        optionTextComponent.text = optionText;
        optionTextComponent.fontSize = config.fontSize;
        optionTextComponent.color = ParseColor(config.fontColor);
        optionTextComponent.alignment = TextAlignmentOptions.Center;
        optionTextComponent.verticalAlignment = VerticalAlignmentOptions.Middle;
        
        // Configurer la position
        int optionIndex = hole.options.IndexOf(optionText);
        optionRect.anchoredPosition = new Vector2(0, -optionIndex * config.itemHeight);
    }
    
    private void SelectOption(string option)
    {
        selectedValue = option;
        buttonText.text = option;
        
        // Fermer le dropdown
        CloseDropdown();
        
        // Notifier le changement
        onValueChanged?.Invoke(this, option);
    }
    
    private void ToggleDropdown()
    {
        if (isOpen)
        {
            CloseDropdown();
        }
        else
        {
            OpenDropdown();
        }
    }
    
    private void OpenDropdown()
    {
        isOpen = true;
        dropdownPanel.SetActive(true);
        
        // Animation d'ouverture
        StartCoroutine(AnimateDropdown(true));
    }
    
    private void CloseDropdown()
    {
        isOpen = false;
        
        // Animation de fermeture
        StartCoroutine(AnimateDropdown(false));
    }
    
    private System.Collections.IEnumerator AnimateDropdown(bool opening)
    {
        float duration = config.animationDuration;
        float elapsed = 0f;
        
        Vector3 startScale = opening ? Vector3.zero : Vector3.one;
        Vector3 endScale = opening ? Vector3.one : Vector3.zero;
        
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float t = elapsed / duration;
            
            dropdownPanel.transform.localScale = Vector3.Lerp(startScale, endScale, t);
            
            yield return null;
        }
        
        dropdownPanel.transform.localScale = endScale;
        
        if (!opening)
        {
            dropdownPanel.SetActive(false);
        }
    }
    
    public string GetSelectedValue()
    {
        return selectedValue;
    }
    
    public void SetCorrect(bool correct)
    {
        isCorrect = correct;
        
        // Changer la couleur selon la réponse
        Color color = correct ? Color.green : Color.red;
        buttonText.color = color;
        
        // Optionnel: désactiver le dropdown si correct
        if (correct)
        {
            dropdownButton.interactable = false;
        }
    }
    
    public bool IsCorrect()
    {
        return isCorrect;
    }
    
    private Color ParseColor(string colorString)
    {
        if (ColorUtility.TryParseHtmlString(colorString, out Color color))
        {
            return color;
        }
        return Color.white;
    }
    
    private void OnDestroy()
    {
        if (dropdownButton != null)
        {
            dropdownButton.onClick.RemoveAllListeners();
        }
    }
}
