using UnityEngine;
using System.Collections;

/// <summary>
/// Enhanced Travel Event System that provides player choice for combat encounters
/// Integrates CombatEventPopup for better user experience
/// </summary>
public class EnhancedTravelEventSystem : MonoBehaviour
{
    [Header("Enhanced Event System")]
    public CombatEventPopup combatEventPopup;
    public bool allowRunningAway = true;
    [Range(0f, 1f)]
    public float runAwaySuccessChance = 0.75f;
    public int runAwayHealthPenalty = 5;

    [Header("Run Away Messages")]
    [TextArea(2, 4)]
    public string[] successfulRunAwayMessages = {
        "Your party successfully escapes from the enemies!",
        "Quick thinking allows your party to avoid the confrontation!",
        "Your party slips away unnoticed by the enemies."
    };

    [TextArea(2, 4)]
    public string[] failedRunAwayMessages = {
        "The enemies catch up to your party! You take {damage} damage while trying to escape.",
        "Your escape attempt fails! The enemies pursue and wound your party for {damage} damage.",
        "The enemies block your escape route! Your party suffers {damage} damage in the failed attempt."
    };

    // Component references
    private TravelEventSystem originalEventSystem;
    private TravelEventUI eventUI;

    // Current combat state
    private BattleEventData pendingBattleData;
    private TravelEventContext pendingContext;
    private bool waitingForCombatDecision = false;

    void Start()
    {
        // Find required components
        originalEventSystem = FindFirstObjectByType<TravelEventSystem>();
        eventUI = FindFirstObjectByType<TravelEventUI>();

        if (combatEventPopup == null)
            combatEventPopup = FindFirstObjectByType<CombatEventPopup>();

        if (originalEventSystem == null)
        {
            Debug.LogError("❌ Enhanced Travel Event System requires a TravelEventSystem component!");
            enabled = false;
            return;
        }

        if (combatEventPopup == null)
        {
            Debug.LogError("❌ Enhanced Travel Event System requires a CombatEventPopup component!");
            enabled = false;
            return;
        }

        // Setup combat popup callback
        combatEventPopup.OnCombatDecision += HandleCombatDecision;

        Debug.Log("✅ Enhanced Travel Event System initialized");
    }

    void OnDestroy()
    {
        if (combatEventPopup != null)
            combatEventPopup.OnCombatDecision -= HandleCombatDecision;
    }

    /// <summary>
    /// Enhanced combat event handler that shows popup before battle
    /// Call this instead of the original HandleBattleEvent
    /// </summary>
    public void HandleEnhancedBattleEvent(BattleEventData battleData, TravelEventContext context, string eventDescription)
    {
        if (battleData == null || waitingForCombatDecision)
            return;

        Debug.Log($"🎭 Enhanced battle event triggered: {eventDescription}");

        // Store pending battle data
        pendingBattleData = battleData;
        pendingContext = context;
        waitingForCombatDecision = true;

        // Show combat popup
        combatEventPopup.ShowCombatEncounter(battleData, context, eventDescription);
    }

    /// <summary>
    /// Handle the player's combat decision from the popup
    /// </summary>
    private void HandleCombatDecision(bool chooseToAttack)
    {
        if (!waitingForCombatDecision || pendingBattleData == null)
            return;

        waitingForCombatDecision = false;

        if (chooseToAttack)
        {
            HandleAttackChoice();
        }
        else
        {
            HandleRunAwayChoice();
        }

        // Clear pending data
        pendingBattleData = null;
        pendingContext = null;
    }

    /// <summary>
    /// Handle when player chooses to attack
    /// </summary>
    private void HandleAttackChoice()
    {
        Debug.Log("⚔️ Player chose to fight! Setting up battle...");

        // Call the original battle setup logic
        if (originalEventSystem != null)
        {
            // Use reflection to call the private HandleBattleEvent method
            var method = originalEventSystem.GetType().GetMethod("HandleBattleEvent",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            if (method != null)
            {
                method.Invoke(originalEventSystem, new object[] { pendingBattleData, pendingContext });
            }
            else
            {
                Debug.LogError("❌ Could not find HandleBattleEvent method in TravelEventSystem");
                // Fallback: just log the battle setup
                LogBattleSetup(pendingBattleData);
            }
        }
    }

    /// <summary>
    /// Handle when player chooses to run away
    /// </summary>
    private void HandleRunAwayChoice()
    {
        Debug.Log("🏃 Player chose to run away! Rolling for escape...");

        if (!allowRunningAway)
        {
            Debug.Log("❌ Running away is not allowed! Forcing combat...");
            HandleAttackChoice();
            return;
        }

        bool escapeSuccessful = Random.value <= runAwaySuccessChance;

        if (escapeSuccessful)
        {
            HandleSuccessfulEscape();
        }
        else
        {
            HandleFailedEscape();
        }
    }

    /// <summary>
    /// Handle successful escape attempt
    /// </summary>
    private void HandleSuccessfulEscape()
    {
        string message = successfulRunAwayMessages[Random.Range(0, successfulRunAwayMessages.Length)];

        Debug.Log($"✅ Escape successful: {message}");

        // Show escape message
        if (eventUI != null)
        {
            eventUI.ShowEventMessage(message, EventType.Discovery, false);
        }
        else
        {
            Debug.Log($"📜 ESCAPE: {message}");
        }

        // Continue travel (no resource penalties for successful escape)
        ResumeTravelAfterEvent();
    }

    /// <summary>
    /// Handle failed escape attempt
    /// </summary>
    private void HandleFailedEscape()
    {
        string message = failedRunAwayMessages[Random.Range(0, failedRunAwayMessages.Length)];
        message = message.Replace("{damage}", runAwayHealthPenalty.ToString());

        Debug.Log($"❌ Escape failed: {message}");

        // Apply health penalty
        ApplyRunAwayPenalty();

        // Show failure message
        if (eventUI != null)
        {
            eventUI.ShowEventMessage(message, EventType.Hazard, false);
        }
        else
        {
            Debug.Log($"📜 ESCAPE FAILED: {message}");
        }

        // Start combat anyway
        StartCoroutine(DelayedCombatStart());
    }

    /// <summary>
    /// Apply penalties for failed escape attempt
    /// </summary>
    private void ApplyRunAwayPenalty()
    {
        // This would integrate with your character health system
        Debug.Log($"❤️ Party takes {runAwayHealthPenalty} damage from failed escape attempt");

        // TODO: Actually apply health damage to party members
        // Example: TeamHealthManager.ApplyDamageToParty(runAwayHealthPenalty);
    }

    /// <summary>
    /// Resume travel after successful escape
    /// </summary>
    private void ResumeTravelAfterEvent()
    {
        // The travel system should continue normally
        Debug.Log("🚗 Resuming travel after event...");

        // No need to stop travel for successful escapes
    }

    /// <summary>
    /// Start combat after a delay (for failed escape)
    /// </summary>
    private IEnumerator DelayedCombatStart()
    {
        yield return new WaitForSeconds(3f); // Wait for escape message to be read

        Debug.Log("⚔️ Starting combat after failed escape...");
        HandleAttackChoice();
    }

    /// <summary>
    /// Fallback battle setup logging
    /// </summary>
    private void LogBattleSetup(BattleEventData battleData)
    {
        Debug.Log($"⚔️ Setting up battle: {battleData.enemyCount} {battleData.enemyType}(s)");

        if (battleData.enemyCharacterData != null)
        {
            Debug.Log($"🎯 Using enemy data: {battleData.enemyCharacterData.enemyName}");
            Debug.Log($"📊 Enemy stats: HP={battleData.enemyCharacterData.maxHealth}, " +
                     $"AC={battleData.enemyCharacterData.armorClass}, " +
                     $"Threat={battleData.enemyCharacterData.threatLevel}");
        }

        // TODO: Actually set up battle scene transition
        Debug.Log("🎬 Transitioning to battle scene...");
    }

    /// <summary>
    /// Check if the system is currently waiting for player input
    /// </summary>
    public bool IsWaitingForCombatDecision => waitingForCombatDecision;

    /// <summary>
    /// Cancel pending combat (for cleanup)
    /// </summary>
    public void CancelPendingCombat()
    {
        if (waitingForCombatDecision)
        {
            waitingForCombatDecision = false;
            pendingBattleData = null;
            pendingContext = null;

            if (combatEventPopup != null)
                combatEventPopup.ForceClose();
        }
    }
}
