using UnityEngine;

public class HUDManager : MonoBehaviour {
    public static HUDManager Instance { get; private set; }

    [SerializeField] private GameObject _computerHUD;
    [SerializeField] private GameObject _sellScreenHUD;
    [SerializeField] private GameObject _miniGameHud;
    [SerializeField] private GameObject _dayEndHUD;
    [SerializeField] private GameObject _repairHUD;

    private GameObject _currentHUD;

    public bool IsUiOpen => _currentHUD != null;

    private void Awake() {
        if (Instance != null) {
            Debug.LogError("What? 2 HudManagers crazy!!!");
        }

        Instance = this;
    }

    private void Update() {
        CheckClose();
    }

    public void ShowComputerHUD() {
        ShowHUD(_computerHUD);
    }

    public void ShowSellScreenHUD(SellCounter counter) {
        ShowHUD(_sellScreenHUD);
    }

    public void ShowDayEndHUD() {
        ShowHUD(_dayEndHUD);
    }

    private void ShowHUD(GameObject hud) {
        if (_currentHUD != null) {
            _currentHUD.SetActive(false);
        }

        _currentHUD = hud;
        _currentHUD.SetActive(true);
    }

    public void HideCurrentHUD() {
        if (_currentHUD != null) {
            _currentHUD.SetActive(false);
            _currentHUD = null;
        }
    }

    private void CheckClose() {
        if (!Input.GetKeyDown(KeyCode.Escape)) return;
        if (_currentHUD == null) return;

        HideCurrentHUD();
    }


    public void SellItem(SellCounter counter, Object sellingObject) {
        Debug.Log(_sellScreenHUD.GetComponent<SellScreenController>());
        this.ShowSellScreenHUD(counter);
        _sellScreenHUD.GetComponent<SellScreenController>().SetItem(counter, sellingObject);
    }

    public void BuyItem(ComputerBehaviour computerBehaviour, ObjectSO objectSo, bool isBroken) {
        this.ShowMinigameHUD();
        this._miniGameHud.GetComponent<MinigameScreenController>().BuyItem(computerBehaviour, objectSo, isBroken);
    }

    private void ShowMinigameHUD() {
        ShowHUD(_miniGameHud);
    }

    public DayEndHUDController GetDayEndController() {
        return _dayEndHUD.GetComponent<DayEndHUDController>();
    }

    public void UpdateItem(ObjectSO objectToSell, bool isBroken) {
        this._miniGameHud.GetComponent<MinigameScreenController>().UpdateItem(objectToSell, isBroken);
    }

    public void ShowRepairHUD() {
        ShowHUD(_repairHUD);
    }

    public void SetRepairHudItem(RepairStationBehaviour repairStationBehaviour, Object @object, float timeToFix,
        float costToFix) {
        _repairHUD.GetComponent<RepairHudController>().SetObject(repairStationBehaviour, @object, timeToFix, costToFix);
    }
}