using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public enum GameState
    {
        InMainMenu,
        Paused,
        Playing,
        GameOver,
        Won
    }

    public static GameManager gameManagerInstance { get; private set; }

    [SerializeField] int currentOrbCounter = 0;
    [SerializeField] int maximumOrbs = 10;

    [SerializeField] TextMeshProUGUI orbCounterText;

    [SerializeField] float timeUntilNightfall = 180f;
    [SerializeField] TextMeshProUGUI timerText;

    public GameState gameState = GameState.InMainMenu;

    private void Awake()
    {
        if(gameManagerInstance == null)
        {
            gameManagerInstance = this;

            DontDestroyOnLoad(gameObject);

            SceneManager.sceneLoaded += OnSceneLoaded;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if(scene.name == "Sandbox")
        {
            GameObject orbObject = GameObject.Find("Orb_Text");
            if (orbObject)
            {
                orbCounterText = orbObject.GetComponent<TextMeshProUGUI>();
            }

            GameObject timerObject = GameObject.Find("Timer");
            if (timerObject)
            {
                timerText = timerObject.GetComponent<TextMeshProUGUI>();
            }

            UpdateOrbUI();
        }
    }

    private void Update()
    {
        if(gameState == GameState.Playing)
        {
            HandleTimer();
        }
    }

    private void HandleTimer()
    {
        if(timeUntilNightfall > 0)
        {
            timeUntilNightfall -= Time.deltaTime;
            UpdateTimerUI();
        }
        else
        {
            timeUntilNightfall = 0;
            GameOver();
        }
    }

    private void UpdateTimerUI()
    {
        if (timerText)
        {
            int minutes = Mathf.FloorToInt(timeUntilNightfall / 60);
            int seconds = Mathf.FloorToInt(timeUntilNightfall % 60);
            timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
        }
    }

    public void IncreaseOrbCounter()
    {
        currentOrbCounter++;
        UpdateOrbUI();
        CheckAllOrbsCollected();
    }

    private void UpdateOrbUI()
    {
        if(orbCounterText != null)
        {
            orbCounterText.text = currentOrbCounter + "/" + maximumOrbs;
        }
    }

    private void CheckAllOrbsCollected()
    {
        if(currentOrbCounter >= maximumOrbs)
        {
            gameState = GameState.Won;
            SceneManager.LoadScene("VictoryScene");
        }
    }

    private void GameOver()
    {
        gameState = GameState.GameOver;
        SceneManager.LoadScene("GameOverScene");
    }

    public void StartGame()
    {
        currentOrbCounter = 0;
        gameState = GameState.Playing;
        SceneManager.LoadScene("Sandbox");
    }
}
