using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

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

    [Header("Scene Transition")]
    public bool useLoadingScreen = false;
    public float minimumLoadingTime = 1f;

    // Scene name constants for easy reference
    public const string TITLE_SCENE = "TitleScreen";
    public const string TEAM_SELECT_SCENE = "MainTeamSelectScene";
    public const string BATTLE_SETUP_SCENE = "BattleSetupMenu";
    public const string BATTLE_SCENE = "BattleScene";
    public const string MAP_SCENE = "MapScene";

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

    #region Public Scene Navigation Methods

    public void GoToTitleScreen()
    {
        LoadScene(TITLE_SCENE);
    }

    public void GoToTeamSelect()
    {
        LoadScene(TEAM_SELECT_SCENE);
    }

    public void GoToBattleSetup()
    {
        LoadScene(BATTLE_SETUP_SCENE);
    }

    public void GoToBattle()
    {
        LoadScene(BATTLE_SCENE);
    }

    public void GoToMapScene()
    {
        LoadScene(MAP_SCENE);
    }

    #endregion

    #region Core Scene Loading

    public void LoadScene(string sceneName)
    {
        if (string.IsNullOrEmpty(sceneName))
        {
            Debug.LogError("Scene name is null or empty!");
            return;
        }



        if (useLoadingScreen)
        {
            StartCoroutine(LoadSceneWithLoadingScreen(sceneName));
        }
        else
        {
            SceneManager.LoadScene(sceneName);
        }
    }

    public void LoadSceneAsync(string sceneName, System.Action onComplete = null)
    {
        StartCoroutine(LoadSceneAsyncCoroutine(sceneName, onComplete));
    }

    private IEnumerator LoadSceneWithLoadingScreen(string sceneName)
    {
        // TODO: Show loading screen UI here
        yield return new WaitForSeconds(0.1f); // Brief delay to show loading screen

        float startTime = Time.time;

        // Start loading the scene asynchronously
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
        asyncLoad.allowSceneActivation = false;

        // Wait for the scene to be ready or minimum loading time
        while (!asyncLoad.isDone)
        {
            float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f);

            // TODO: Update loading screen progress here


            // If loading is done and minimum time has passed, activate the scene
            if (asyncLoad.progress >= 0.9f && (Time.time - startTime) >= minimumLoadingTime)
            {
                asyncLoad.allowSceneActivation = true;
            }

            yield return null;
        }

        // TODO: Hide loading screen UI here
    }

    private IEnumerator LoadSceneAsyncCoroutine(string sceneName, System.Action onComplete)
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);

        while (!asyncLoad.isDone)
        {
            yield return null;
        }

        onComplete?.Invoke();
    }

    #endregion

    #region Scene Validation

    public bool IsSceneInBuildSettings(string sceneName)
    {
        for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
        {
            string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
            string sceneNameFromPath = System.IO.Path.GetFileNameWithoutExtension(scenePath);

            if (sceneNameFromPath.Equals(sceneName, System.StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
        }
        return false;
    }

    public string GetCurrentSceneName()
    {
        return SceneManager.GetActiveScene().name;
    }

    #endregion

    #region Development/Debug Methods

    [System.Diagnostics.Conditional("UNITY_EDITOR")]
    public void LogAllScenesInBuild()
    {

        for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
        {
            string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
            string sceneName = System.IO.Path.GetFileNameWithoutExtension(scenePath);

        }
    }

    #endregion
}
