using GatherAndDefend.Events;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public abstract class UnitPlacementButton : PlacementButton, IPointerEnterHandler, IPointerExitHandler
{
    [SerializeField]
    protected Sprite _detectionRangeSprite;

    [SerializeField]
    protected UnitCard _unitCardInformation;
  
    [SerializeField]
    private TMP_Text _foodLabel;
    [SerializeField]
    private TMP_Text _woodLabel;
    [SerializeField]
    private TMP_Text _rockLabel;

    [SerializeField]
    protected Image _cooldownIndicator;
    protected bool _lockedByCooldown;

    protected override void Start()
    {
        base.Start();
    }

    protected override void Update()
    {
        base.Update();

        SetTextFor(_foodLabel, _unitCardInformation.Food);
        SetTextFor(_rockLabel, _unitCardInformation.Rock);
        SetTextFor(_woodLabel, _unitCardInformation.Wood);
    }
    void SetTextFor(TMP_Text label, int value)
    {
        label.transform.parent.gameObject.SetActive(value > 0);
        label.text = "" + value;
    }
    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        if (Placeholder is UnitPlaceholder placeHolder)
        {
            placeHolder.Rock = _unitCardInformation.Rock;
            placeHolder.Wood = _unitCardInformation.Wood;
            placeHolder.Food = _unitCardInformation.Food;
            placeHolder.WasPlaced += HandleCooldown;
        }
        
    }

    private void HandleCooldown(UnitPlaceholder unitPlaceholder)
    {
        unitPlaceholder.WasPlaced -= HandleCooldown;
        StartCoroutine(HandleCooldownCoroutine());
            

        IEnumerator HandleCooldownCoroutine() 
        {
            var countDown = 0f;
            _lockedByCooldown = true;
            _cooldownIndicator.gameObject.SetActive(true);
            while (countDown < _unitCardInformation.CooldownInSeconds)
            {
                countDown += Time.deltaTime;
                var percentDone = countDown / _unitCardInformation.CooldownInSeconds;
                _cooldownIndicator.fillAmount = 1 - percentDone;
                yield return null;
            }
            _cooldownIndicator.gameObject.SetActive(false);
            _lockedByCooldown = false;
        }
    }

    protected override bool CanPlace()
    {
        return base.CanPlace() && !_lockedByCooldown;
    }

    public virtual void OnPointerEnter(PointerEventData eventData){}

    public virtual void OnPointerExit(PointerEventData eventData){}
}
