using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

public class GameManager : MonoBehaviour
{
    public TMP_Text roundTimerText;
    public TMP_Text spawnTimerText;
    public TMP_Text gameOverText;
    public TMP_Text p1ScoreText;
    public TMP_Text p2ScoreText;
    public TMP_Text winnerText;

    public float roundDuration = 60f;
    private float spawnInterval = 20f;
    private float roundTimer;
    private float spawnTimer;

    private int p1Score = 0;
    private int p2Score = 0;

    private int currentLevel = 1; // Start at Level 1
    private const int totalLevels = 3; // Total number of levels

    public static GameManager Instance;

    private void Awake()
    {
        // Singleton pattern
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject); // Persist across scenes
    }

    private void Start()
    {
        InitializeUI();

        roundTimer = roundDuration;
        spawnTimer = spawnInterval;
    }

    private void Update()
    {
        if (roundTimer <= 0) return;

        roundTimer -= Time.deltaTime;
        spawnTimer -= Time.deltaTime;

        // Update round timer display
        if (roundTimerText != null)
            roundTimerText.text = $"Time Left: {Mathf.CeilToInt(roundTimer)}s";

        // Update spawn timer display
        if (spawnTimerText != null)
            spawnTimerText.text = $"Next Spawn: {Mathf.CeilToInt(spawnTimer)}s";

        // End round when timer reaches 0
        if (roundTimer <= 0)
        {
            EndRound();
        }
    }

    private void EndRound()
    {
        roundTimer = 0;

        // Clear bubbles or other objects if needed
        BubbleSpawner.Instance?.ClearBubbles();

        Debug.Log("Round Ended!");

        if (currentLevel < totalLevels)
        {
            // Go to the next level
            currentLevel++;
            LoadNextLevel();
        }
        else
        {
            // All levels are done; go to the StartScreen
            GoToStartScreen();
        }
    }

    private void LoadNextLevel()
    {
        // Load the next level scene
        SceneManager.LoadScene($"Level_{currentLevel}");

        // Re-initialize and reset the UI timers for the next round
        roundTimer = roundDuration;
        spawnTimer = spawnInterval;

        // Make sure the timers are visible and the UI elements are reset
        roundTimerText.gameObject.SetActive(true);
        spawnTimerText.gameObject.SetActive(true);
        gameOverText.gameObject.SetActive(false);
        winnerText.gameObject.SetActive(false);

        // Reset score displays
        if (p1ScoreText != null) p1ScoreText.text = $"Player 1: {p1Score}";
        if (p2ScoreText != null) p2ScoreText.text = $"Player 2: {p2Score}";

        Debug.Log($"Loading Level {currentLevel}...");
    }

    private void GoToStartScreen()
    {
        // Load the StartScreen scene
        SceneManager.LoadScene("StartScreen");

        // Optionally reset scores and other game state
        p1Score = 0;
        p2Score = 0;
        if (p1ScoreText != null) p1ScoreText.text = $"Player 1: {p1Score}";
        if (p2ScoreText != null) p2ScoreText.text = $"Player 2: {p2Score}";

        Debug.Log("Game Over! Returning to Start Screen...");
    }

    private void DisplayGameOver()
    {
        if (gameOverText != null)
        {
            gameOverText.text = "Game Over!";
            gameOverText.gameObject.SetActive(true);
        }

        // Determine and display the winner
        string winner = DetermineWinner();
        if (winnerText != null)
        {
            winnerText.text = $"{winner} Wins!";
            winnerText.gameObject.SetActive(true);
        }

        // Optionally disable other UI elements
        roundTimerText?.gameObject.SetActive(false);
        spawnTimerText?.gameObject.SetActive(false);
    }

    private string DetermineWinner()
    {
        if (p1Score > p2Score)
        {
            return "Player 1";
        }
        else if (p2Score > p1Score)
        {
            return "Player 2";
        }
        else
        {
            return "It's a Tie!";
        }
    }

    public void UpdateP1Score()
    {
        p1Score++;
        if (p1ScoreText != null)
            p1ScoreText.text = $"Player 1: {p1Score}";
    }

    public void UpdateP2Score()
    {
        p2Score++;
        if (p2ScoreText != null)
            p2ScoreText.text = $"Player 2: {p2Score}";
    }

    private void InitializeUI()
    {
        if (roundTimerText == null) Debug.LogError("Round Timer Text (TMP) is not assigned!");
        if (spawnTimerText == null) Debug.LogError("Spawn Timer Text (TMP) is not assigned!");
        if (gameOverText == null) Debug.LogError("Game Over Text (TMP) is not assigned!");
        if (p1ScoreText == null) Debug.LogError("Player 1 Score Text (TMP) is not assigned!");
        if (p2ScoreText == null) Debug.LogError("Player 2 Score Text (TMP) is not assigned!");
        if (winnerText == null) Debug.LogError("Winner Text (TMP) is not assigned!");

        if (gameOverText != null)
            gameOverText.gameObject.SetActive(false);
        if (winnerText != null)
            winnerText.gameObject.SetActive(false);
    }
}
