using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Abilities
{
    public class StartingBlackDieAbility : MonoBehaviour
    {
        public static event Action AbilitySelected;
        
        [SerializeField] protected GameObject abilityUseOne;
        [SerializeField] protected GameObject abilityUseTwo;
        [SerializeField] protected GameObject abilityUseThree;
        private int _uses = 3;
        
        private GameObject[] _usesUsed;
        private bool _canClick;

        protected virtual void OnEnable() {
            GameManager.StateChanged += HandleStateChanged;
        }

        protected virtual void OnDisable() {
            GameManager.StateChanged -= HandleStateChanged;
        }

        private void Start() {
            _usesUsed = new GameObject[_uses];
            abilityUseOne.GetComponent<Button>().onClick.AddListener(() => UseClicked(abilityUseOne));
            abilityUseTwo.GetComponent<Button>().onClick.AddListener(() => UseClicked(abilityUseTwo));
            abilityUseThree.GetComponent<Button>().onClick.AddListener(() => UseClicked(abilityUseThree));
        }

        private void UseClicked(GameObject abilityUseObject) {
            if (!_canClick) return;

            if (_uses > 0)
            {
                _usesUsed[_uses - 1] = abilityUseObject;
                MarkUseUsed(abilityUseObject);
                AbilitySelected?.Invoke();
                _uses -= 1;
            }

            _canClick = false;
        }

        private void MarkUseUsed(GameObject useObject) {
            useObject.GetComponentInChildren<TextMeshProUGUI>().text = "X";
        }

        private void UnmarkUseUsed(GameObject useObject) {
            useObject.GetComponentInChildren<TextMeshProUGUI>().text = string.Empty;
        }

        public void AbilitySelectedButNotUsed() {
            UnmarkUseUsed(_usesUsed[_uses - 1]);
            _uses += 1;
        }

        private void HandleStateChanged(GameState state) {
            switch (state)
            {
                case GameState.PickDiceOne:
                case GameState.PickDiceTwo:
                    _canClick = true;
                    break;
                default:
                    _canClick = false;
                    break;
            }
        }
    }
}
