using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using DG.Tweening;

public class UI : MonoBehaviour {
  public float fadeTime = 0.5f;
  public float fadeSpeed = 10f;

  [Header("References")]
  public CanvasGroup tutorialPane;
  public TMPro.TMP_Text tutorialTitle;
  public TMPro.TMP_Text tutorialDescription;
  public UnityEngine.UI.Image tutorialImage;
  public CanvasGroup infoPane;
  public TMPro.TMP_Text infoText;
  public CanvasGroup fadePane;

  public GameObject holdControl;
  public GameObject cmd1Control;
  public GameObject cmd2Control;

  private float tTargetAlpha = 0f;
  private float iTargetAlpha = 0f;
  private float tutorialDismissTimer;
  private float infoDismissTimer;
  private Rewired.Player rwplayer;

  private Flags flags;

  private void Awake() {
    rwplayer = Rewired.ReInput.players.GetPlayer(0);
    tutorialPane.alpha = 0f;
    infoPane.alpha = 0f;
    flags = Flags.Instance;
  }

  private void Update() {
    tutorialDismissTimer -= Time.deltaTime;
    infoDismissTimer -= Time.deltaTime;

    holdControl.SetActive(flags.FoundAnyRedCrystal);
    cmd1Control.SetActive(flags.GolemBondLevel >= 1);
    cmd2Control.SetActive(flags.GolemBondLevel >= 2);

    var anyButton = rwplayer.GetAnyButton();

    if (tutorialDismissTimer < 0f && anyButton) {
      DismissTutorial();
    }

    if (infoDismissTimer < 0f) {
      DismissInfo();
    }

    tutorialPane.alpha = Mathf.Lerp(tutorialPane.alpha, tTargetAlpha, Time.deltaTime * fadeSpeed);
    infoPane.alpha = Mathf.Lerp(infoPane.alpha, iTargetAlpha, Time.deltaTime * fadeSpeed);
  }

  private void OnEnable() {
    SceneManager.sceneLoaded += OnSceneLoaded;
  }

  private void OnDisable() {
    SceneManager.sceneLoaded -= OnSceneLoaded;
  }

  public Tween FadeOutScene() {
    return fadePane.DOFade(1f, 0.5f);
  }

  public void ShowTutorial(string title, string description, Sprite icon) {
    infoPane.alpha = iTargetAlpha = 0f;
    tutorialImage.sprite = icon;
    tutorialTitle.text = title;
    tutorialDescription.text = description;
    tutorialDismissTimer = 3f;
    tTargetAlpha = 1f;
  }

  public void DismissTutorial() {
    tTargetAlpha = 0f;
  }

  public void ShowInfo(string info) {
    infoText.text = info;
    infoDismissTimer = 2.5f;
    iTargetAlpha = 1f;
  }

  public void DismissInfo() {
    iTargetAlpha = 0f;
  }

  private void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
    fadePane.DOFade(0f, 1f);
  }

  private static UI _instance;
  public static UI Instance {
    get {
      if (_instance == null) {
        _instance = GameObject.FindGameObjectWithTag("GameController").GetComponentInChildren<UI>();
      }
      return _instance;
    }
  }
}
