using UnityEngine;
using System.Collections.Generic;
using UnityEngine.AI;

/// <summary>
/// Enhanced BattleSetup that works with CombatDataTransfer for richer combat initialization
/// Extends the existing BattleSetup functionality with team data and terrain information
/// </summary>
public class EnhancedBattleSetup : MonoBehaviour
{
    [Header("Enhanced Combat Setup")]
    [Tooltip("Enable enhanced setup using CombatDataTransfer")]
    public bool useEnhancedSetup = true;

    [Header("UI Elements")]
    [Tooltip("UI Text to display battle context (terrain, weather, etc.)")]
    public UnityEngine.UI.Text battleContextText;

    [Header("Terrain Setup")]
    [Tooltip("Terrain generator for setting up battle environment")]
    public BFMTerrainGenerator terrainGenerator;

    [Header("Debug")]
    public bool showDebugLogs = true;

    // Reference to original BattleSetup if needed
    private BattleSetup originalBattleSetup;

    void Start()
    {
        // Get reference to original BattleSetup component
        originalBattleSetup = GetComponent<BattleSetup>();

        if (useEnhancedSetup && CombatDataTransfer.HasValidSession())
        {
            SetupEnhancedCombat();
        }
        else
        {
            if (showDebugLogs)
            {
                Debug.Log("🔧 Enhanced setup disabled or no combat session - using standard BattleSetup");
            }
        }
    }

    /// <summary>
    /// Set up combat using the enhanced CombatDataTransfer system
    /// </summary>
    private void SetupEnhancedCombat()
    {
        var session = CombatDataTransfer.GetCurrentSession();
        if (session == null)
        {
            Debug.LogError("❌ No combat session data available!");
            return;
        }

        if (showDebugLogs)
        {
            Debug.Log("🎯 Setting up enhanced combat...");
            CombatDataTransfer.DebugLogSession();
        }

        // Set up terrain
        SetupBattleTerrain(session);

        // Update UI with battle context
        UpdateBattleContextUI(session);

        // The original BattleSetup will handle character placement using BattleSetupData
        // which was already populated by CombatDataTransfer.PopulateLegacyBattleSetupData()

        if (showDebugLogs)
        {
            Debug.Log("✅ Enhanced combat setup complete");
        }
    }

    /// <summary>
    /// Set up the battle terrain based on combat session data
    /// </summary>
    private void SetupBattleTerrain(CombatDataTransfer.CombatSessionData session)
    {
        if (terrainGenerator == null)
        {
            terrainGenerator = FindFirstObjectByType<BFMTerrainGenerator>();
        }

        if (terrainGenerator != null)
        {
            BFMTerrainType bfmTerrain = ConvertToBFMTerrainType(session.battleTerrain);

            if (showDebugLogs)
            {
                Debug.Log($"🌍 Setting battle terrain: {bfmTerrain} (from {session.battleTerrain})");
            }

            terrainGenerator.SetTerrainType(bfmTerrain);

            // If there's a regenerate method, call it
            // terrainGenerator.RegenerateTerrain(); // Uncomment if this method exists
        }
        else
        {
            if (showDebugLogs)
            {
                Debug.LogWarning("⚠️ No BFMTerrainGenerator found - terrain setup skipped");
            }
        }
    }

    /// <summary>
    /// Update UI elements with battle context information
    /// </summary>
    private void UpdateBattleContextUI(CombatDataTransfer.CombatSessionData session)
    {
        if (battleContextText != null)
        {
            string terrainDesc = CombatDataTransfer.GetTerrainDescription(session.battleTerrain, session.battleFeature);
            string timeDesc = GetTimeDescription(session.timeOfDay);
            string weatherDesc = session.weather.ToString().ToLower();

            string contextDescription = $"Battle {terrainDesc}\\n{timeDesc.ToUpper()} - {weatherDesc} weather";
            battleContextText.text = contextDescription;

            if (showDebugLogs)
            {
                Debug.Log($"🎨 Updated battle context UI: {contextDescription}");
            }
        }
    }

    /// <summary>
    /// Convert TerrainType to BFMTerrainType
    /// </summary>
    private BFMTerrainType ConvertToBFMTerrainType(TerrainType terrainType)
    {
        return terrainType switch
        {
            TerrainType.Plains => BFMTerrainType.Plain,
            TerrainType.Forest => BFMTerrainType.Forest,
            TerrainType.Mountain => BFMTerrainType.Mountain,
            TerrainType.ForestRiver => BFMTerrainType.Forest,
            _ => BFMTerrainType.Plain
        };
    }

    /// <summary>
    /// Convert time of day to readable description
    /// </summary>
    private string GetTimeDescription(float timeOfDay)
    {
        return timeOfDay switch
        {
            >= 6f and < 12f => "morning",
            >= 12f and < 18f => "afternoon",
            >= 18f and < 22f => "evening",
            _ => "night"
        };
    }

    /// <summary>
    /// Get enhanced character stats for a team member
    /// </summary>
    public static void ApplyEnhancedStats(GameObject characterObject, CombatDataTransfer.TeamCharacterCombatData combatData)
    {
        if (characterObject == null || combatData == null) return;

        var character = characterObject.GetComponent<Character>();
        if (character != null)
        {
            // Apply enhanced stats from combat data
            character.CharacterName = combatData.characterName;

            // Apply combat stats if the Character component supports them
            // character.MaxHealth = combatData.maxHealth; // Uncomment if property exists
            // character.CurrentHealth = combatData.currentHealth;
            // character.ArmorClass = combatData.armorClass;

            Debug.Log($"📊 Applied enhanced stats to {combatData.characterName}: HP={combatData.currentHealth}/{combatData.maxHealth}, AC={combatData.armorClass}");
        }
    }

    /// <summary>
    /// Get enhanced enemy stats for an enemy character
    /// </summary>
    public static void ApplyEnhancedEnemyStats(GameObject enemyObject, CombatDataTransfer.EnemyCombatData enemyData)
    {
        if (enemyObject == null || enemyData == null) return;

        var character = enemyObject.GetComponent<Character>();
        if (character != null)
        {
            character.CharacterName = enemyData.enemyName;

            // Apply enhanced enemy stats
            // character.MaxHealth = enemyData.maxHealth; // Uncomment if property exists
            // character.CurrentHealth = enemyData.currentHealth;
            // character.ArmorClass = enemyData.armorClass;

            Debug.Log($"👹 Applied enhanced enemy stats to {enemyData.enemyName}: HP={enemyData.currentHealth}/{enemyData.maxHealth}, AC={enemyData.armorClass}, Threat={enemyData.threatLevel}");
        }
    }

    /// <summary>
    /// Debug method to show current combat session info
    /// </summary>
    [ContextMenu("Debug Combat Session")]
    public void DebugCombatSession()
    {
        if (CombatDataTransfer.HasValidSession())
        {
            CombatDataTransfer.DebugLogSession();
        }
        else
        {
            Debug.Log("🔍 No active combat session");
        }
    }

    /// <summary>
    /// Method to be called when battle ends to clean up
    /// </summary>
    public void EndBattleSession(bool playerVictory)
    {
        if (showDebugLogs)
        {
            Debug.Log($"🏆 Battle ended - Player victory: {playerVictory}");
        }

        // Find and use CombatSceneManager to handle the end
        var combatSceneManager = FindFirstObjectByType<MonoBehaviour>();
        if (combatSceneManager != null && combatSceneManager.GetType().Name == "CombatSceneManager")
        {
            var method = combatSceneManager.GetType().GetMethod("EndCombatSession");
            if (method != null)
            {
                method.Invoke(combatSceneManager, new object[] { playerVictory });
            }
        }
        else
        {
            // Fallback: just clear the session
            CombatDataTransfer.ClearSession();
            Debug.Log("🧹 Combat session cleared (no CombatSceneManager found)");
        }
    }
}
