using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.SceneManagement;
using System.IO;

public class TitleScreenManager : MonoBehaviour
{
    private UIDocument uiDocument;
    private Button newGameButton;
    private Button loadGameButton;
    private Button quitButton;

    private void Awake()
    {
        uiDocument = GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("UIDocument component not found on TitleScreenManager GameObject.");
            return;
        }

        SetupUI();
    }

    private void Start()
    {
        // Refresh the load game button state on start
        // This ensures it reflects the current save data status
        UpdateLoadGameButton();
    }

    private void SetupUI()
    {
        var root = uiDocument.rootVisualElement;

        // Get button references
        newGameButton = root.Q<Button>("NewGameButton");
        loadGameButton = root.Q<Button>("LoadGameButton");
        quitButton = root.Q<Button>("QuitButton");

        // Setup button events
        if (newGameButton != null)
        {
            newGameButton.clicked += OnNewGameClicked;
        }
        else
        {
            Debug.LogWarning("NewGameButton not found in UI Document");
        }

        if (loadGameButton != null)
        {
            loadGameButton.clicked += OnLoadGameClicked;
            // Check if there's a saved game and disable button if not
            UpdateLoadGameButton();
        }
        else
        {
            Debug.LogWarning("LoadGameButton not found in UI Document");
        }

        if (quitButton != null)
        {
            quitButton.clicked += OnQuitClicked;
        }
        else
        {
            Debug.LogWarning("QuitButton not found in UI Document");
        }
    }

    private void OnNewGameClicked()
    {
        Debug.Log("=== NEW GAME BUTTON CLICKED ===");

        // Check if there's an existing save game
        if (HasSavedGame())
        {
            // Show warning dialog about overwriting save data
            ShowNewGameWarning();
            return;
        }

        StartNewGame();
    }

    private void ShowNewGameWarning()
    {
        Debug.Log("Warning: Existing save game detected!");

        // For now, we'll use Unity's dialog system. In a full game, you'd create a proper UI dialog
#if UNITY_EDITOR
        bool confirmed = UnityEditor.EditorUtility.DisplayDialog(
            "New Game Warning",
            "You have an existing saved game. Starting a new game will overwrite your current progress.\n\nDo you want to continue?",
            "Start New Game",
            "Cancel"
        );

        if (confirmed)
        {
            StartNewGame();
        }
#else
        // In builds, we'll assume user confirms for now
        // In a real game, implement a proper UI dialog system
        Debug.LogWarning("Existing save detected - proceeding with new game (implement proper dialog for builds)");
        StartNewGame();
#endif
    }

    private void StartNewGame()
    {
        Debug.Log("Starting new game...");

        // Clear any existing save data FIRST, before setting new game flag
        Debug.Log($"🔍 Before ClearSaveData(): IsNewGame = {PlayerPrefs.GetInt("IsNewGame", -1)}");
        ClearSaveData();
        PlayerPrefs.SetInt("IsNewGame", 1); // Set new game flag
        PlayerPrefs.Save();
        Debug.Log($"🔍 After ClearSaveData(): IsNewGame = {PlayerPrefs.GetInt("IsNewGame", -1)}");

        // Initialize GameStateManager for new game (this sets the IsNewGame flag)
        if (GameStateManager.Instance != null)
        {
            GameStateManager.Instance.StartNewGame();
            Debug.Log($"🔍 After GameStateManager.StartNewGame(): IsNewGame = {PlayerPrefs.GetInt("IsNewGame", -1)}");
        }

        // Try to load the main team select scene
        string targetScene = "MainTeamSelectScene";

        if (SceneExists(targetScene))
        {
            SceneManager.LoadScene(targetScene);
        }
        else
        {
            Debug.LogError($"Scene '{targetScene}' not found in Build Settings! Please add it to Build Settings.");
            // Let's also log all available scenes for debugging
            LogAllScenesInBuild();
        }
    }

    private void OnLoadGameClicked()
    {
        Debug.Log("=== LOAD GAME BUTTON CLICKED ===");
        Debug.Log("Loading saved game...");

        // Debug current PlayerPrefs state before making any decisions
        DebugCurrentPlayerPrefsState();

        // Double-check if we have a saved game (this should always be true due to button state)
        if (HasSavedGame())
        {
            // Initialize/Load the GameStateManager
            if (GameStateManager.Instance != null)
            {
                GameStateManager.Instance.LoadGame();
                Debug.Log($"GameStateManager loaded: teamSetupComplete={GameStateManager.Instance.teamSetupComplete}, hasGeneratedMap={GameStateManager.Instance.hasGeneratedMap}");
            }
            else
            {
                Debug.Log("GameStateManager.Instance is null - relying on PlayerPrefs only");
            }

            // Determine where to go based on game progress
            // If we have completed characters AND they have proceeded past team setup, go to MapScene2
            // Otherwise, go to team selection to allow modifications
            bool shouldGoToMap = ShouldLoadDirectlyToMap();

            if (shouldGoToMap)
            {
                // Team is ready and has progressed past setup, go to MapScene2
                string targetScene = "MapScene2";
                Debug.Log($"Team is complete and game has progressed! Loading {targetScene}...");

                if (SceneExists(targetScene))
                {
                    SceneManager.LoadScene(targetScene);
                }
                else
                {
                    Debug.LogError($"Scene '{targetScene}' not found! Falling back to MainTeamSelectScene");
                    SceneManager.LoadScene("MainTeamSelectScene");
                }
            }
            else
            {
                // Team setup not complete or hasn't progressed, go to team selection
                string targetScene = "MainTeamSelectScene";
                Debug.Log($"Team setup incomplete or hasn't progressed past setup. Loading {targetScene}...");

                if (SceneExists(targetScene))
                {
                    SceneManager.LoadScene(targetScene);
                }
                else
                {
                    Debug.LogError($"Scene '{targetScene}' not found in Build Settings!");
                    LogAllScenesInBuild();
                }
            }
        }
        else
        {
            Debug.LogWarning("Load Game clicked but no saved game found!");
            // Update button state to reflect current save status
            UpdateLoadGameButton();
        }
    }

    private void DebugCurrentPlayerPrefsState()
    {
        Debug.Log("=== CURRENT PLAYERPREFS STATE ===");

        // Check team completion flags
        bool teamSetupComplete = PlayerPrefs.HasKey("TeamSetupComplete") && PlayerPrefs.GetInt("TeamSetupComplete") == 1;
        bool hasGeneratedMap = PlayerPrefs.HasKey("HasGeneratedMap") && PlayerPrefs.GetInt("HasGeneratedMap") == 1;

        Debug.Log($"TeamSetupComplete: {teamSetupComplete} (raw: {PlayerPrefs.GetInt("TeamSetupComplete", -1)})");
        Debug.Log($"HasGeneratedMap: {hasGeneratedMap} (raw: {PlayerPrefs.GetInt("HasGeneratedMap", -1)})");

        // Check characters
        int characterCount = 0;
        for (int i = 0; i < 4; i++)
        {
            string existsKey = $"Character{i}_Exists";
            bool exists = PlayerPrefs.HasKey(existsKey) && PlayerPrefs.GetInt(existsKey) == 1;
            if (exists)
            {
                characterCount++;
                string name = PlayerPrefs.GetString($"Character{i}_Name", "UNKNOWN");
                Debug.Log($"Character {i}: {name} (exists)");
            }
        }

        Debug.Log($"Total characters: {characterCount}");
        Debug.Log("=== END PLAYERPREFS STATE ===");
    }

    private bool ShouldLoadDirectlyToMap()
    {
        // Check if the game has progressed beyond initial team setup
        // This means: team is complete AND they have clicked "Proceed to Battle" at least once

        // First check if we have any characters
        if (!HasSavedGame()) return false;

        // Check if GameStateManager indicates team setup is complete
        bool teamComplete = false;
        if (GameStateManager.Instance != null)
        {
            teamComplete = GameStateManager.Instance.teamSetupComplete;
            Debug.Log($"GameStateManager found: teamSetupComplete = {teamComplete}");
        }
        else
        {
            Debug.Log("No GameStateManager found, checking PlayerPrefs for team completion");
        }

        // If GameStateManager doesn't indicate completion, check PlayerPrefs directly
        if (!teamComplete)
        {
            // Count characters
            int characterCount = 0;
            for (int i = 0; i < 4; i++)
            {
                if (PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
                {
                    characterCount++;
                }
            }

            // Check if team setup was marked complete in PlayerPrefs
            bool teamSetupCompleteInPrefs = PlayerPrefs.HasKey("TeamSetupComplete") && PlayerPrefs.GetInt("TeamSetupComplete") == 1;

            // Check if the game has been started (indicated by map generation)
            bool hasGeneratedMap = PlayerPrefs.HasKey("HasGeneratedMap") && PlayerPrefs.GetInt("HasGeneratedMap") == 1;

            // Team is complete if we have characters AND (team setup complete OR map generated)
            teamComplete = characterCount > 0 && (teamSetupCompleteInPrefs || hasGeneratedMap);

            Debug.Log($"PlayerPrefs check: characters={characterCount}, teamSetupComplete={teamSetupCompleteInPrefs}, hasGeneratedMap={hasGeneratedMap}");
        }

        Debug.Log($"ShouldLoadDirectlyToMap: final result = {teamComplete}");
        return teamComplete;
    }

    private void OnQuitClicked()
    {
        Debug.Log("Quitting game...");

#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
    }

    private void UpdateLoadGameButton()
    {
        if (loadGameButton != null)
        {
            bool hasSavedGame = HasSavedGame();
            Debug.Log($"UpdateLoadGameButton: HasSavedGame = {hasSavedGame}");

            // Disable the button if no saved game
            loadGameButton.SetEnabled(hasSavedGame);

            if (!hasSavedGame)
            {
                loadGameButton.AddToClassList("disabled-button");
                loadGameButton.tooltip = "No saved game available";
                // Make the button visually appear disabled
                loadGameButton.style.opacity = 0.5f;
                // Remove click event temporarily by replacing it
                loadGameButton.clicked -= OnLoadGameClicked;
            }
            else
            {
                loadGameButton.RemoveFromClassList("disabled-button");
                loadGameButton.tooltip = "Load your saved game";
                loadGameButton.style.opacity = 1.0f;
                // Re-add click event if not already added
                loadGameButton.clicked -= OnLoadGameClicked; // Remove first to prevent duplicates
                loadGameButton.clicked += OnLoadGameClicked;
            }
        }
    }

    private bool HasSavedGame()
    {
        // Check if we have any characters saved
        // Look for at least one character that exists
        for (int i = 0; i < 4; i++)
        {
            if (PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
            {
                return true;
            }
        }
        return false;
    }

    private bool SceneExists(string sceneName)
    {
        // Check if scene is in build settings
        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;
    }

    private void ClearSaveData()
    {
        Debug.Log("🧹 TitleScreenManager.ClearSaveData() - clearing save data but preserving IsNewGame flag");

        // Clear character data
        for (int i = 0; i < 4; i++)
        {
            string prefix = $"Character{i}_";
            PlayerPrefs.DeleteKey(prefix + "Exists");
            PlayerPrefs.DeleteKey(prefix + "Name");
            PlayerPrefs.DeleteKey(prefix + "IsMale");
            PlayerPrefs.DeleteKey(prefix + "Strength");
            PlayerPrefs.DeleteKey(prefix + "Dexterity");
            PlayerPrefs.DeleteKey(prefix + "Constitution");
            PlayerPrefs.DeleteKey(prefix + "Wisdom");
            PlayerPrefs.DeleteKey(prefix + "Gold");
            PlayerPrefs.DeleteKey(prefix + "Silver");
            PlayerPrefs.DeleteKey(prefix + "Copper");
        }

        // Clear team finalization flags - THIS WAS MISSING!
        PlayerPrefs.DeleteKey("TeamSetupComplete");
        PlayerPrefs.DeleteKey("HasGeneratedMap");

        // Clear map data
        PlayerPrefs.DeleteKey("MapSeed");
        PlayerPrefs.DeleteKey("MapWidth");
        PlayerPrefs.DeleteKey("MapHeight");
        PlayerPrefs.DeleteKey("MapNoiseScale");
        PlayerPrefs.DeleteKey("MapOceanThreshold");
        PlayerPrefs.DeleteKey("MapMountainThreshold");
        PlayerPrefs.DeleteKey("MapForestThreshold");

        // NOTE: We explicitly DO NOT clear "IsNewGame" here - it needs to persist

        PlayerPrefs.Save();
        Debug.Log("Save data cleared for new game - including team finalization flags");
    }

    private void OnEnable()
    {
        // Update load button state when the screen becomes active
        UpdateLoadGameButton();
    }

    private void LogAllScenesInBuild()
    {
        Debug.Log("=== ALL SCENES IN BUILD SETTINGS ===");
        for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
        {
            string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
            string sceneName = Path.GetFileNameWithoutExtension(scenePath);
            Debug.Log($"Index {i}: {sceneName} ({scenePath})");
        }
        Debug.Log("=== END SCENE LIST ===");
    }

    // Call this from inspector for debugging
    [ContextMenu("Check Build Settings")]
    public void CheckBuildSettings()
    {
        LogAllScenesInBuild();

        bool mainTeamSelectExists = SceneExists("MainTeamSelectScene");
        Debug.Log($"MainTeamSelectScene in Build Settings: {mainTeamSelectExists}");

        bool hasSave = HasSavedGame();
        Debug.Log($"Has saved game: {hasSave}");
    }
}
