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

public class TorchAbility : MonoBehaviour
{
    public static
        event Action TorchAbilityUsed;
    [SerializeField] private GameObject abilityUseOne;
    [SerializeField] private GameObject abilityUseTwo;

    private int _uses = 2;
    private GameObject[] _usesUsed;
    private bool _canClick;

    private void OnEnable()
    {
        GameManager.StateChanged += HandleStateChanged;
        ChestRewardSelection.TorchAbilitySelected += HandleGainedTorchAbility;
    }

    private void OnDisable()
    {
        GameManager.StateChanged -= HandleStateChanged;
        ChestRewardSelection.TorchAbilitySelected -= HandleGainedTorchAbility;
    }

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

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

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

        _canClick = false;
    }

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

    private void HandleStateChanged(GameState state)
    {
        _canClick = true;
    }

    private void HandleGainedTorchAbility()
    {
        abilityUseOne.GetComponent<Button>().interactable = true;
        abilityUseTwo.GetComponent<Button>().interactable = true;
    }
}
