using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using YachtDice.Modifiers.Runtime;

namespace YachtDice.Inventory
{
    public class InventorySlotView : MonoBehaviour
    {
        [SerializeField] private Image iconImage;
        [SerializeField] private TMP_Text nameText;
        [SerializeField] private TMP_Text descriptionText;
        [SerializeField] private TMP_Text usesText;
        [SerializeField] private Button activateButton;
        [SerializeField] private Button deactivateButton;
        [SerializeField] private Button sellButton;
        [SerializeField] private TMP_Text sellPriceText;
        [SerializeField] private Image background;

        [Header("Colors")]
        [SerializeField] private Color activeColor = new(0.7f, 1f, 0.7f);
        [SerializeField] private Color inactiveColor = Color.white;

        private ModifierInstance instance;

        public event Action<ModifierInstance> OnActivateClicked;
        public event Action<ModifierInstance> OnDeactivateClicked;
        public event Action<ModifierInstance> OnSellClicked;

        private void Awake()
        {
            if (activateButton != null)
                activateButton.onClick.AddListener(() => OnActivateClicked?.Invoke(instance));
            if (deactivateButton != null)
                deactivateButton.onClick.AddListener(() => OnDeactivateClicked?.Invoke(instance));
            if (sellButton != null)
                sellButton.onClick.AddListener(() => OnSellClicked?.Invoke(instance));
        }

        public void Setup(ModifierInstance modifierInstance, bool canActivateMore)
        {
            instance = modifierInstance;
            var def = instance.Definition;

            if (def == null) return;

            if (nameText != null) nameText.text = def.DisplayName;
            if (descriptionText != null) descriptionText.text = def.Description;
            if (iconImage != null && def.Icon != null) iconImage.sprite = def.Icon;

            if (usesText != null)
            {
                if (def.HasLimitedUses)
                {
                    usesText.gameObject.SetActive(true);
                    usesText.text = $"{instance.RemainingUses}/{def.MaxUses}";
                }
                else
                {
                    usesText.gameObject.SetActive(false);
                }
            }

            if (sellPriceText != null) sellPriceText.text = def.SellPrice.ToString();

            bool isActive = instance.IsActive;

            if (activateButton != null)
            {
                activateButton.gameObject.SetActive(!isActive);
                activateButton.interactable = canActivateMore;
            }

            if (deactivateButton != null)
                deactivateButton.gameObject.SetActive(isActive);

            if (background != null)
                background.color = isActive ? activeColor : inactiveColor;
        }
    }
}
