using UnityEngine;
using UnityEngine.UIElements;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.SceneManagement;

/// <summary>
/// Controls the TeamOverview UI panel on the right side of the map scene.
/// Displays current team information, stats, and provides navigation controls.
/// Works with the main map UI document.
/// </summary>
public class TeamOverviewController : MonoBehaviour
{
    [Header("Settings")]
    [SerializeField] public bool showDebugLogs = false;

    // UI Elements
    private VisualElement teamOverviewPanel;
    private ScrollView teamMembersList;
    private Button manageTeamButton;
    private Button saveGameButton;
    private Label memberCountLabel;
    private Label totalGoldLabel;
    private Label averageLevelLabel;
    private Toggle perceptionVisualizationToggle;

    // UI Document reference (shared with map)
    private UIDocument uiDocument;

    // Team data
    private List<TeamCharacter> currentTeam;

    void Awake()
    {
        // Get the UIDocument component from this GameObject
        uiDocument = GetComponent<UIDocument>();
        if (uiDocument == null)
        {
            Debug.LogError("❌ TeamOverviewController: No UIDocument component found on this GameObject!");
        }
    }

    void Start()
    {
        // Ensure GameStateManager has loaded data if it exists
        if (GameStateManager.Instance != null && PlayerPrefs.HasKey("GameSaved"))
        {
            GameStateManager.Instance.LoadGame();
        }

        SetupUI();
        LoadTeamData();
        ShowTeamOverview();
    }

    /// <summary>
    /// Sets up the UI elements and event handlers
    /// </summary>
    private void SetupUI()
    {
        if (uiDocument?.rootVisualElement == null)
        {
            Debug.LogError("❌ TeamOverviewController: UIDocument not found or has no root element!");
            return;
        }

        var root = uiDocument.rootVisualElement;

        // Find UI elements - using the correct button names from TeamOverview.uxml
        teamOverviewPanel = root.Q("TeamOverviewPanel");
        teamMembersList = root.Q<ScrollView>("TeamMembersList");
        manageTeamButton = root.Q<Button>("ReturnToTeamSelectButton");
        saveGameButton = root.Q<Button>("SaveGameButton");
        memberCountLabel = root.Q<Label>("MemberCountLabel");
        totalGoldLabel = root.Q<Label>("TotalGoldLabel");
        averageLevelLabel = root.Q<Label>("AverageLevelLabel");
        perceptionVisualizationToggle = root.Q<Toggle>("PerceptionVisualizationToggle");

        // Debug: Check which elements were found
        if (showDebugLogs)
        {
            Debug.Log($"🔍 UI Elements found:");
            Debug.Log($"   TeamOverviewPanel: {teamOverviewPanel != null}");
            Debug.Log($"   TeamMembersList: {teamMembersList != null}");
            Debug.Log($"   ManageTeamButton: {manageTeamButton != null}");
            Debug.Log($"   SaveGameButton: {saveGameButton != null}");
            Debug.Log($"   MemberCountLabel: {memberCountLabel != null}");
            Debug.Log($"   TotalGoldLabel: {totalGoldLabel != null}");
            Debug.Log($"   AverageLevelLabel: {averageLevelLabel != null}");
            Debug.Log($"   PerceptionVisualizationToggle: {perceptionVisualizationToggle != null}");
        }

        // Setup event handlers
        if (manageTeamButton != null)
        {
            manageTeamButton.clicked += OnManageTeamClicked;
        }

        if (saveGameButton != null)
        {
            saveGameButton.clicked += OnSaveGameClicked;
        }

        if (perceptionVisualizationToggle != null)
        {
            // Load saved toggle state
            bool savedState = PlayerPrefs.GetInt("ShowPerceptionVisualization", 1) == 1;
            perceptionVisualizationToggle.value = savedState;

            // Set up event handler
            perceptionVisualizationToggle.RegisterValueChangedCallback(OnPerceptionVisualizationToggled);

            // Apply initial state to visualizer
            UpdatePerceptionVisualizationState(savedState);
        }

        if (showDebugLogs)
        {
            Debug.Log("✅ TeamOverviewController: UI setup complete");
        }
    }

    /// <summary>
    /// Loads current team data from the save system
    /// </summary>
    private void LoadTeamData()
    {
        currentTeam = new List<TeamCharacter>();

        // Method 1: Try to load from MainTeamSelectScript (if in TeamSelect scene)
        var teamSelectScript = FindFirstObjectByType<MainTeamSelectScript>();
        if (teamSelectScript != null)
        {
            currentTeam = teamSelectScript.GetConfiguredCharacters();
            if (showDebugLogs)
            {
                Debug.Log($"📋 Loaded team from MainTeamSelectScript: {currentTeam.Count} members");
            }
            return;
        }

        // Method 2: Try to load from GameStateManager
        if (GameStateManager.Instance != null && GameStateManager.Instance.savedTeam != null)
        {
            foreach (var character in GameStateManager.Instance.savedTeam)
            {
                if (character != null)
                {
                    currentTeam.Add(character);
                }
            }
            if (currentTeam.Count > 0)
            {
                if (showDebugLogs)
                {
                    Debug.Log($"📋 Loaded team from GameStateManager: {currentTeam.Count} members");
                }
                return;
            }
        }

        // Method 3: Try to load directly from PlayerPrefs (fallback)
        for (int i = 0; i < 4; i++)
        {
            string prefix = $"Character{i}_";
            if (PlayerPrefs.HasKey(prefix + "Exists") && PlayerPrefs.GetInt(prefix + "Exists") == 1)
            {
                var character = new TeamCharacter();
                character.name = PlayerPrefs.GetString(prefix + "Name", "");
                character.isMale = PlayerPrefs.GetInt(prefix + "IsMale", 1) == 1;
                character.strength = PlayerPrefs.GetInt(prefix + "Strength", 10);
                character.dexterity = PlayerPrefs.GetInt(prefix + "Dexterity", 10);
                character.constitution = PlayerPrefs.GetInt(prefix + "Constitution", 10);
                character.wisdom = PlayerPrefs.GetInt(prefix + "Wisdom", 10);
                character.perception = PlayerPrefs.GetInt(prefix + "Perception", 10);
                character.gold = PlayerPrefs.GetInt(prefix + "Gold", 25);
                character.silver = PlayerPrefs.GetInt(prefix + "Silver", 0);
                character.copper = PlayerPrefs.GetInt(prefix + "Copper", 0);

                if (!string.IsNullOrEmpty(character.name))
                {
                    currentTeam.Add(character);
                }
            }
        }

        if (currentTeam.Count > 0)
        {
            if (showDebugLogs)
            {
                Debug.Log($"📋 Loaded team from PlayerPrefs: {currentTeam.Count} members");
            }
        }
        else
        {
            if (showDebugLogs)
            {
                Debug.Log("ℹ️ No team data found - this is normal for a new game");
            }
        }
    }    /// <summary>
         /// Shows the team overview panel
         /// </summary>
    public void ShowTeamOverview()
    {
        if (teamOverviewPanel == null) return;

        teamOverviewPanel.style.display = DisplayStyle.Flex;
        UpdateTeamDisplay();

        if (showDebugLogs)
        {
            Debug.Log("👥 TeamOverviewController: Team overview panel shown");
        }
    }

    /// <summary>
    /// Hides the team overview panel
    /// </summary>
    public void HideTeamOverview()
    {
        if (teamOverviewPanel == null) return;

        teamOverviewPanel.style.display = DisplayStyle.None;

        if (showDebugLogs)
        {
            Debug.Log("👻 TeamOverviewController: Team overview panel hidden");
        }
    }

    /// <summary>
    /// Updates the team display with current data
    /// </summary>
    private void UpdateTeamDisplay()
    {
        if (currentTeam == null)
        {
            if (showDebugLogs)
            {
                Debug.Log("⚠️ UpdateTeamDisplay: currentTeam is null");
            }
            return;
        }

        if (teamMembersList == null)
        {
            if (showDebugLogs)
            {
                Debug.Log("⚠️ UpdateTeamDisplay: teamMembersList is null - UI elements not found");
            }
            return;
        }

        if (showDebugLogs)
        {
            Debug.Log($"🎨 UpdateTeamDisplay: Updating display for {currentTeam.Count} team members");
        }

        // Clear existing team member displays
        teamMembersList.Clear();

        // Add each team member
        foreach (var member in currentTeam)
        {
            if (member != null)
            {
                CreateTeamMemberCard(member);
                if (showDebugLogs)
                {
                    Debug.Log($"📋 Added card for member: {member.name}");
                }
            }
        }

        // Update team stats
        UpdateTeamStats();

        if (showDebugLogs)
        {
            Debug.Log($"✅ UpdateTeamDisplay: Display updated with {currentTeam.Count} members");
        }
    }

    /// <summary>
    /// Creates a visual card for a team member
    /// </summary>
    private void CreateTeamMemberCard(TeamCharacter member)
    {
        var memberCard = new VisualElement();
        memberCard.style.backgroundColor = new StyleColor(new Color(0.3f, 0.3f, 0.3f, 0.8f));
        memberCard.style.borderTopColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
        memberCard.style.borderBottomColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
        memberCard.style.borderLeftColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
        memberCard.style.borderRightColor = new StyleColor(new Color(0.5f, 0.5f, 0.5f));
        memberCard.style.borderTopWidth = 1;
        memberCard.style.borderBottomWidth = 1;
        memberCard.style.borderLeftWidth = 1;
        memberCard.style.borderRightWidth = 1;
        memberCard.style.borderTopLeftRadius = 4;
        memberCard.style.borderTopRightRadius = 4;
        memberCard.style.borderBottomLeftRadius = 4;
        memberCard.style.borderBottomRightRadius = 4;
        memberCard.style.marginBottom = 8;
        memberCard.style.paddingTop = 8;
        memberCard.style.paddingBottom = 8;
        memberCard.style.paddingLeft = 8;
        memberCard.style.paddingRight = 8;

        // Member header with name and level
        var memberHeader = new VisualElement();
        memberHeader.style.flexDirection = FlexDirection.Row;
        memberHeader.style.justifyContent = Justify.SpaceBetween;
        memberHeader.style.alignItems = Align.Center;
        memberHeader.style.marginBottom = 5;

        var nameLabel = new Label(member.name);
        nameLabel.style.color = new StyleColor(new Color(1f, 1f, 1f));
        nameLabel.style.fontSize = 12;
        nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;

        var hpLabel = new Label($"HP: {member.HitPoints} | AC: {member.ArmorClass}");
        hpLabel.style.color = new StyleColor(new Color(0.8f, 0.8f, 1f));
        hpLabel.style.fontSize = 10;

        memberHeader.Add(nameLabel);
        memberHeader.Add(hpLabel);
        memberCard.Add(memberHeader);

        // Stats container
        var statsContainer = new VisualElement();
        statsContainer.style.flexDirection = FlexDirection.Row;
        statsContainer.style.flexWrap = Wrap.Wrap;
        statsContainer.style.justifyContent = Justify.SpaceBetween;

        // Add attribute stats in a compact layout
        AddCompactStatLabel(statsContainer, "STR", member.strength);
        AddCompactStatLabel(statsContainer, "DEX", member.dexterity);
        AddCompactStatLabel(statsContainer, "CON", member.constitution);
        AddCompactStatLabel(statsContainer, "WIS", member.wisdom);
        AddCompactStatLabel(statsContainer, "PER", member.perception);

        memberCard.Add(statsContainer);

        teamMembersList.Add(memberCard);
    }

    /// <summary>
    /// Adds a compact stat label to a container
    /// </summary>
    private void AddCompactStatLabel(VisualElement container, string statName, int statValue)
    {
        var statElement = new VisualElement();
        statElement.style.flexDirection = FlexDirection.Row;
        statElement.style.width = new StyleLength(new Length(18, LengthUnit.Percent));
        statElement.style.marginBottom = 1;

        var statLabel = new Label($"{statName}:");
        statLabel.style.color = new StyleColor(new Color(0.8f, 0.8f, 0.8f));
        statLabel.style.fontSize = 9;
        statLabel.style.width = new StyleLength(new Length(60, LengthUnit.Percent));

        var valueLabel = new Label(statValue.ToString());
        valueLabel.style.color = new StyleColor(new Color(1f, 1f, 1f));
        valueLabel.style.fontSize = 9;
        valueLabel.style.width = new StyleLength(new Length(40, LengthUnit.Percent));

        statElement.Add(statLabel);
        statElement.Add(valueLabel);
        container.Add(statElement);
    }

    /// <summary>
    /// Updates the team summary statistics
    /// </summary>
    private void UpdateTeamStats()
    {
        if (currentTeam == null) return;

        // Update member count
        if (memberCountLabel != null)
        {
            memberCountLabel.text = currentTeam.Count.ToString();
        }

        // Update total gold (assuming team shares resources)
        if (totalGoldLabel != null)
        {
            var totalGold = currentTeam.Sum(member => member.gold);
            totalGoldLabel.text = totalGold.ToString();
        }

        // Since TeamCharacter doesn't have level property, assume level 1 for all characters
        if (averageLevelLabel != null)
        {
            averageLevelLabel.text = "1";
        }
    }

    /// <summary>
    /// Handle manage team button click
    /// </summary>
    private void OnManageTeamClicked()
    {
        if (showDebugLogs)
        {
            Debug.Log("🔄 TeamOverviewController: Returning to Team Select scene");
        }

        // Load the Team Select scene
        var sceneManager = FindFirstObjectByType<SceneNavigationManager>();
        if (sceneManager != null)
        {
            sceneManager.GoToTeamSelect();
        }
        else
        {
            // Fallback to direct scene loading
            UnityEngine.SceneManagement.SceneManager.LoadScene("TeamSelect");
        }
    }

    /// <summary>
    /// Handle save game button click
    /// </summary>
    private void OnSaveGameClicked()
    {
        if (showDebugLogs)
        {
            Debug.Log("💾 TeamOverviewController: Saving game");
        }

        try
        {
            // Use GameStateManager to save current game state
            var gameStateManager = FindFirstObjectByType<GameStateManager>();
            if (gameStateManager != null)
            {
                gameStateManager.SaveGame();
                Debug.Log("✅ Game saved successfully!");
            }
            else
            {
                Debug.LogWarning("⚠️ GameStateManager not found!");
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError($"❌ Failed to save game: {e.Message}");
        }
    }

    /// <summary>
    /// Handle perception visualization toggle change
    /// </summary>
    private void OnPerceptionVisualizationToggled(ChangeEvent<bool> evt)
    {
        bool newValue = evt.newValue;

        if (showDebugLogs)
        {
            Debug.Log($"👁️ TeamOverviewController: Perception visualization toggled to {newValue}");
        }

        // Save the setting
        PlayerPrefs.SetInt("ShowPerceptionVisualization", newValue ? 1 : 0);
        PlayerPrefs.Save();

        // Update the visualizer
        UpdatePerceptionVisualizationState(newValue);
    }

    /// <summary>
    /// Updates the perception visualization state
    /// </summary>
    private void UpdatePerceptionVisualizationState(bool enabled)
    {
        var visualizer = TeamPerceptionVisualizer.Instance;
        if (visualizer != null)
        {
            visualizer.SetPerceptionVisualizationEnabled(enabled);
        }
        else if (showDebugLogs)
        {
            Debug.LogWarning("⚠️ TeamPerceptionVisualizer instance not found");
        }
    }

    /// <summary>
    /// Refreshes the team data and display
    /// </summary>
    public void RefreshTeamData()
    {
        LoadTeamData();
        UpdateTeamDisplay();

        if (showDebugLogs)
        {
            Debug.Log("🔄 TeamOverviewController: Team data refreshed");
        }
    }

    /// <summary>
    /// Forces a reload of team data from all sources
    /// </summary>
    public void ForceReloadTeamData()
    {
        // Force GameStateManager to reload if possible
        if (GameStateManager.Instance != null && PlayerPrefs.HasKey("GameSaved"))
        {
            GameStateManager.Instance.LoadGame();
        }

        LoadTeamData();
        UpdateTeamDisplay();

        if (showDebugLogs)
        {
            Debug.Log("🔄 TeamOverviewController: Team data force reloaded");
        }
    }

    /// <summary>
    /// Context menu methods for debugging
    /// </summary>
    [ContextMenu("Show Team Overview")]
    public void TestShowTeamOverview()
    {
        ShowTeamOverview();
    }

    [ContextMenu("Hide Team Overview")]
    public void TestHideTeamOverview()
    {
        HideTeamOverview();
    }

    [ContextMenu("Refresh Team Data")]
    public void TestRefreshTeamData()
    {
        RefreshTeamData();
    }

    [ContextMenu("Force Reload Team Data")]
    public void TestForceReloadTeamData()
    {
        ForceReloadTeamData();
    }

    [ContextMenu("Debug Team Data Sources")]
    public void DebugTeamDataSources()
    {
        Debug.Log("=== TEAM DATA DEBUG ===");

        // Check MainTeamSelectScript
        var teamSelectScript = FindFirstObjectByType<MainTeamSelectScript>();
        Debug.Log($"MainTeamSelectScript found: {teamSelectScript != null}");
        if (teamSelectScript != null)
        {
            var characters = teamSelectScript.GetConfiguredCharacters();
            Debug.Log($"MainTeamSelectScript characters: {characters.Count}");
        }

        // Check GameStateManager
        Debug.Log($"GameStateManager.Instance: {GameStateManager.Instance != null}");
        if (GameStateManager.Instance != null)
        {
            Debug.Log($"GameStateManager.savedTeam: {GameStateManager.Instance.savedTeam != null}");
            if (GameStateManager.Instance.savedTeam != null)
            {
                int count = 0;
                foreach (var character in GameStateManager.Instance.savedTeam)
                {
                    if (character != null) count++;
                }
                Debug.Log($"GameStateManager team count: {count}");
            }
        }

        // Check PlayerPrefs
        int playerPrefsCount = 0;
        for (int i = 0; i < 4; i++)
        {
            if (PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
            {
                string name = PlayerPrefs.GetString($"Character{i}_Name", "");
                if (!string.IsNullOrEmpty(name))
                {
                    playerPrefsCount++;
                    Debug.Log($"PlayerPrefs Character {i}: {name}");
                }
            }
        }
        Debug.Log($"PlayerPrefs character count: {playerPrefsCount}");

        Debug.Log($"Current team loaded: {currentTeam?.Count ?? 0}");
        if (currentTeam != null)
        {
            foreach (var member in currentTeam)
            {
                Debug.Log($"  - {member?.name ?? "null"} (STR:{member?.strength ?? 0}, DEX:{member?.dexterity ?? 0}, CON:{member?.constitution ?? 0}, WIS:{member?.wisdom ?? 0}, PER:{member?.perception ?? 0})");
            }
        }
        Debug.Log("=== END DEBUG ===");
    }

    [ContextMenu("Force Update Display")]
    public void ForceUpdateDisplay()
    {
        if (currentTeam != null && currentTeam.Count > 0)
        {
            Debug.Log($"🔄 Force updating display with {currentTeam.Count} team members");
            UpdateTeamDisplay();
        }
        else
        {
            Debug.Log("⚠️ No team data to display");
        }
    }
}
