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

public class UpgradePlacementButton : MonoBehaviour, IPointerClickHandler
{
    private Button _button;

    [SerializeField]
    private Material _outlineMaterial;
    [SerializeField]
    protected UnitCard _unitCardInformation;

    [SerializeField]
    private TMP_Text _foodLabel;
    [SerializeField]
    private TMP_Text _woodLabel;
    [SerializeField]
    private TMP_Text _rockLabel;
    [SerializeField]
    private GameObject _prefab;
    [SerializeField]
    private Image _image;
    [SerializeField]
    private Image _unitArt;
    [SerializeField]
    private GameObject _buttonContainer;
    private GameObject _unitGameObject;
    private Canvas _canvas;


    public Button Button => _button;
    public Material OutlineMaterial => _outlineMaterial;

    void Start()
    {
        _button = GetComponent<Button>();
        _button.enabled = true;
        Debug.Log("Upgrade instantiated...");
    }
    
    void Update()
    {
        if (_unitCardInformation != null)
        {
            _button.interactable = CanUse();
            if (CanUse())
            {
                _image.color = Color.green;
            } else
            {
                _image.color = Color.red;
            }
        }
    }

    private bool CanUse()
    {
        return ResourceManager.Instance.EnoughFor(_unitCardInformation.Rock, _unitCardInformation.Wood, _unitCardInformation.Food);
    }

    void SetTextFor(TMP_Text label, int value)
    {
        label.transform.parent.gameObject.SetActive(value > 0);
        label.text = "" + value;
    }
    
    public void OnPointerClick(PointerEventData eventData)
    {
        if (CanUse())
        {
            //Change parent GameObject
            Vector3 instantiatePosition = _unitGameObject.transform.position;
            Debug.Log("Upgrade clicked...");
            Instantiate(_prefab, instantiatePosition, Quaternion.identity, _canvas.transform);
            ResourceManager resourceManager = ResourceManager.Instance;
            resourceManager.Remove(_unitCardInformation.Rock, _unitCardInformation.Wood, _unitCardInformation.Food);
            Destroy(_unitGameObject);
            Destroy(_buttonContainer);
        }

    }

    public void Initialize(UnitCard card, GameObject prefabGameObject, GameObject parentGameObject, Canvas canvas)
    {
        Debug.Log("Upgrade initialized...");
        SetTextFor(_foodLabel, card.Food);
        SetTextFor(_woodLabel, card.Wood);
        SetTextFor(_rockLabel, card.Rock);
        _unitCardInformation = card;
        _prefab = prefabGameObject;
        _unitGameObject = parentGameObject;
        _canvas = canvas;
    }
}