using TMPro;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;


namespace Gyvr.Mythril2D
{
    public class UISkillListEntry : MonoBehaviour, IPointerEnterHandler, ISelectHandler, IDeselectHandler
    {
        [Header("References")]
        [SerializeField] private Image m_image = null;
        [SerializeField] private TextMeshProUGUI m_name = null;
        [SerializeField] private Button m_button = null;

        [Header("Settings")]
        [SerializeField] private Color m_availableColor;
        [SerializeField] private Color m_unavailableColor;

        private Skill m_target = null;
        private ESkillCategory m_type;

        public void Initialize(Skill skill, ESkillCategory type)
        {
            m_target = skill;
            m_name.text = skill.displayName;
            m_image.sprite = skill.icon;
            m_type = type;
            UpdateUI();
        }

        private void Awake()
        {
            m_button.onClick.AddListener(OnSlotClicked);
        }

        public void UpdateUI()
        {
            bool hasSkill = GameManager.Player.HasSkill(m_target);
            Color textColor = hasSkill ? m_unavailableColor : m_availableColor;
            m_name.color = textColor;

            // Disable button
            m_button.interactable = !hasSkill;
            //Set opasity of the image
            Color imageColor = m_image.color;
            imageColor.a = hasSkill ? 0.5f : 1.0f; // Define opacidade: 0.5 se indisponvel, 1.0 se disponvel
            m_image.color = imageColor;
        }

        public Skill GetTarget()
        {
            return m_target;
        }

        public void ForceSelection()
        {
            m_button.Select();
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            if (m_button.IsInteractable())
            {
                m_button.Select();
            }
        }

        public void OnSelect(BaseEventData eventData)
        {
                GameManager.NotificationSystem.skillDetailsOpened.Invoke(m_target);
        }

        public void OnDeselect(BaseEventData eventData)
        {
                GameManager.NotificationSystem.skillDetailsClosed.Invoke();
        }

        public void OnSlotClicked()
        {
            if (m_target != null)
            {
                SendMessageUpwards("OnSkillSelectedFromList", m_target, SendMessageOptions.RequireReceiver);
            }
        }
    }
}
