using DialogueSystem;
using UniRx;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UIManager : MonoBehaviour
{
    public GameObject pauseMenu;   
    public GameObject winScreen;   
    public GameObject loseScreen;
    public string loseMode = "Canvas"; // Canvas or Scene
    public string loseScene = "Outro";

    public BoolReactiveProperty isPaused = new BoolReactiveProperty(false);
    
    public static UIManager Instance { get; private set; }
    
    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(this);
            return;
        }
        
        Instance = this;
        
    }

    void Start()
    {
        SetPaused(false);
        if (pauseMenu) pauseMenu.SetActive(false);
        if (winScreen) winScreen.SetActive(false);
        if (loseScreen) loseScreen.SetActive(false);
    }

    void Update()
    {
        // toggle pause with Escape
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            // Do not toggle if win/lose screen is active
            if ((winScreen && winScreen.activeSelf) || (loseScreen && loseScreen.activeSelf)) return;
            TogglePause();
        }
    }

    public void TogglePause()
    {
        SetPaused(!isPaused.Value);
    }

    public void SetPaused(bool paused)
    {
        isPaused.Value = paused;
        if (pauseMenu) pauseMenu.SetActive(paused);
        
        // if the tutorial is open underneath the pause screen, we do not set the timescale back.
        // timescale is then set by pressing the x button on the tutorial panel
        if (!DialogueManager.Instance.tutorialIsOpen.Value)
        {
            Time.timeScale = paused ? 0f : 1f;   
        }
    }

    public void OnUnpauseButton() => SetPaused(false);

    //TODO this button from win screen doesnt restard fully. 
    public void OnRestartButton()
    {
        Time.timeScale = 1f;
        AudioManager.Instance.MusicOnNormal();
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    public void OnMainMenuButton(string mainMenuSceneName)
    {
        Time.timeScale = 1f;
        AudioManager.Instance.MusicOnNormal();
        SceneManager.LoadScene(mainMenuSceneName);
    }

    public void OnSceneLoad(string sceneName)
    {
        Time.timeScale = 1f;
        AudioManager.Instance.MusicOnNormal();
        SceneManager.LoadScene(sceneName);
    } 
    
    public void ShowWin()
    {
        Time.timeScale = 0f;
        if (winScreen) winScreen.SetActive(true);
    }

    public void ShowLose()
    {
        Time.timeScale = 0f;
        AudioManager.Instance.MusicOnLoose();
        if (loseMode == "Scene")
        {
            SceneManager.LoadScene(loseScene);
        }
        else if (loseScreen) loseScreen.SetActive(true);
    }
}
