using UnityEngine;
using UnityEngine.UIElements;
using Button = UnityEngine.UIElements.Button;

public class SellScreenController : MonoBehaviour {

    private UIDocument _document;
    
    private Label _itemNameLabel;
    private Label _avgPriceLabel;
    private Label _paidPriceLabel;
    private TextField _yourPriceInputfield;
    
    private SellCounter _counter;
    private Object _sellingObject;

    
    //Because we set the gameobject to active false, we need to use OnEnable
    private void OnEnable() {
        _document = GetComponent<UIDocument>();
        _itemNameLabel = _document.rootVisualElement.Q<Label>("ItemName");
        _document.rootVisualElement.Q<Button>("SellButton").clicked += SellItem;
        
        _avgPriceLabel = _document.rootVisualElement.Q<Label>("PriceLabel");
        _paidPriceLabel = _document.rootVisualElement.Q<Label>("YouPaid");
        _yourPriceInputfield = _document.rootVisualElement.Q<TextField>("YourPriceInputfield");

        if (_itemNameLabel == null) {
            Debug.LogError("Item name not found");
        }
    }
    
    //on sleep
    private void OnDisable() {
        // _document.rootVisualElement.Q<Button>("SellButton").clicked -= SellItem;
        _counter = null;
        _sellingObject = null;
        
        _itemNameLabel.text = "";
        _paidPriceLabel.text = "";
        _avgPriceLabel.text = "";
        
        _yourPriceInputfield.value = "";
    }


    //TODO: ask how to do this, since the gameobjec that renders the ui is not active
    public void SetItem(SellCounter counter, Object @object) {
        _counter = counter;
        _sellingObject = @object;
        _paidPriceLabel.text = @object.PaidPrice.ToString();
        _avgPriceLabel.text = @object.ObjectSo.basePrice.ToString();
        _itemNameLabel.text = @object.ObjectSo.objectName;
    }

    private void SellItem() {
        Debug.Log("Selling: " + _itemNameLabel.text);
        Debug.Log("Selling for: " + _yourPriceInputfield.text);
        _counter.ConfirmSell(_sellingObject, float.Parse(_yourPriceInputfield.text));
        HUDManager.Instance.HideCurrentHUD();
    }

}