using UnityEngine;
using System.Collections;

/// <summary>
/// Simple UI manager for displaying travel event messages
/// Integrates with your existing UI system to show event popups
/// </summary>
public class TravelEventUI : MonoBehaviour
{
    [Header("Event UI Settings")]
    public bool useDebugUI = true; // Use simple debug UI for now
    public float messageDisplayTime = 4f;
    public KeyCode dismissKey = KeyCode.Space;

    [Header("Event Message Queue")]
    public int maxQueuedMessages = 5;

    // Internal state
    private System.Collections.Generic.Queue<EventMessage> messageQueue = new System.Collections.Generic.Queue<EventMessage>();
    private bool isShowingMessage = false;
    private EventMessage currentMessage;
    private float messageTimer = 0f;

    // UI Elements (for future implementation)
    private Canvas eventCanvas;
    private UnityEngine.UI.Text eventText;
    private UnityEngine.UI.Button dismissButton;

    [System.Serializable]
    private class EventMessage
    {
        public string message;
        public EventType eventType;
        public float displayTime;
        public bool requiresPlayerInput;

        public EventMessage(string msg, EventType type, float time = 4f, bool requiresInput = false)
        {
            message = msg;
            eventType = type;
            displayTime = time;
            requiresPlayerInput = requiresInput;
        }
    }

    void Start()
    {
        SetupEventUI();
    }

    void Update()
    {
        HandleEventDisplay();
        HandleInput();
    }

    /// <summary>
    /// Show a travel event message to the player
    /// </summary>
    public void ShowEventMessage(string message, EventType eventType = EventType.Discovery, bool requiresInput = false)
    {
        if (string.IsNullOrEmpty(message)) return;

        var eventMessage = new EventMessage(message, eventType, messageDisplayTime, requiresInput);

        if (messageQueue.Count >= maxQueuedMessages)
        {
            Debug.LogWarning("⚠️ Event message queue full, discarding oldest message");
            messageQueue.Dequeue();
        }

        messageQueue.Enqueue(eventMessage);

        Debug.Log($"📜 Queued event message: {message}");
    }

    /// <summary>
    /// Show an event result with appropriate formatting
    /// </summary>
    public void ShowEventResult(EventResult result)
    {
        if (result == null || !result.eventOccurred) return;

        string message = result.resultMessage;

        // Add resource change information to the message
        if (result.goldChange != 0 || result.healthChange != 0 || result.foodChange != 0)
        {
            message += "\n\nEffects:";
            if (result.goldChange > 0) message += $"\n💰 +{result.goldChange} Gold";
            if (result.goldChange < 0) message += $"\n💰 {result.goldChange} Gold";
            if (result.healthChange > 0) message += $"\n❤️ +{result.healthChange} Health";
            if (result.healthChange < 0) message += $"\n❤️ {result.healthChange} Health";
            if (result.foodChange > 0) message += $"\n🍖 +{result.foodChange} Food";
            if (result.foodChange < 0) message += $"\n🍖 {result.foodChange} Food";
        }

        // Determine event type based on result
        EventType eventType = EventType.Discovery;
        if (result.startBattle) eventType = EventType.Combat;
        else if (result.openTrading) eventType = EventType.Trading;
        else if (result.healthChange < 0) eventType = EventType.Hazard;
        else if (result.healthChange > 0) eventType = EventType.Rest;

        bool requiresInput = result.shouldStopTravel || result.startBattle || result.openTrading;

        ShowEventMessage(message, eventType, requiresInput);
    }

    private void SetupEventUI()
    {
        if (useDebugUI)
        {
            // For now, we'll use the debug console
            Debug.Log("🖥️ Travel Event UI initialized (Debug Mode)");
            return;
        }

        // TODO: Set up proper UI elements
        // This would create or find UI canvas, text elements, buttons, etc.
        // For integration with your existing UI system
    }

    private void HandleEventDisplay()
    {
        // Start showing next message if not currently showing one
        if (!isShowingMessage && messageQueue.Count > 0)
        {
            currentMessage = messageQueue.Dequeue();
            isShowingMessage = true;
            messageTimer = 0f;
            DisplayCurrentMessage();
        }

        // Handle message timing
        if (isShowingMessage && currentMessage != null)
        {
            messageTimer += Time.deltaTime;

            // Auto-dismiss if time expires and no input required
            if (!currentMessage.requiresPlayerInput && messageTimer >= currentMessage.displayTime)
            {
                DismissCurrentMessage();
            }
        }
    }

    private void HandleInput()
    {
        if (!isShowingMessage || currentMessage == null) return;

        // Handle dismiss input
        if (Input.GetKeyDown(dismissKey))
        {
            DismissCurrentMessage();
        }

        // Handle other event-specific inputs
        if (currentMessage != null && currentMessage.requiresPlayerInput)
        {
            // TODO: Handle specific event choices (Accept/Decline trade, etc.)
        }
    }

    private void DisplayCurrentMessage()
    {
        if (currentMessage == null) return;

        if (useDebugUI)
        {
            string prefix = GetEventTypePrefix(currentMessage.eventType);
            Debug.Log($"{prefix} {currentMessage.message}");

            if (currentMessage.requiresPlayerInput)
            {
                Debug.Log($"💡 Press {dismissKey} to continue...");
            }
        }
        else
        {
            // TODO: Display in proper UI
            // Set text content, show panel, animate, etc.
        }
    }

    private void DismissCurrentMessage()
    {
        if (currentMessage == null) return;

        Debug.Log($"✅ Event message dismissed: {currentMessage.eventType}");

        currentMessage = null;
        isShowingMessage = false;
        messageTimer = 0f;

        if (!useDebugUI)
        {
            // TODO: Hide UI elements, animate out, etc.
        }
    }

    private string GetEventTypePrefix(EventType eventType)
    {
        return eventType switch
        {
            EventType.Combat => "⚔️ COMBAT:",
            EventType.Trading => "🛒 TRADING:",
            EventType.Discovery => "💎 DISCOVERY:",
            EventType.Social => "👥 ENCOUNTER:",
            EventType.Hazard => "⚠️ HAZARD:",
            EventType.Rest => "🏕️ REST:",
            EventType.Mystery => "❓ MYSTERY:",
            _ => "📜 EVENT:"
        };
    }

    /// <summary>
    /// Clear all queued messages
    /// </summary>
    public void ClearMessages()
    {
        messageQueue.Clear();
        if (isShowingMessage)
        {
            DismissCurrentMessage();
        }
        Debug.Log("🧹 Event message queue cleared");
    }

    /// <summary>
    /// Check if the UI is currently showing a message that requires input
    /// </summary>
    public bool IsWaitingForInput()
    {
        return isShowingMessage && currentMessage != null && currentMessage.requiresPlayerInput;
    }

    /// <summary>
    /// Get the number of queued messages
    /// </summary>
    public int GetQueuedMessageCount()
    {
        return messageQueue.Count;
    }

    void OnGUI()
    {
        if (!useDebugUI || !isShowingMessage || currentMessage == null) return;

        // Simple on-screen display for debugging
        GUIStyle style = new GUIStyle(GUI.skin.box);
        style.fontSize = 16;
        style.wordWrap = true;
        style.alignment = TextAnchor.MiddleCenter;

        // Background box
        float boxWidth = Screen.width * 0.6f;
        float boxHeight = Screen.height * 0.3f;
        float boxX = (Screen.width - boxWidth) * 0.5f;
        float boxY = (Screen.height - boxHeight) * 0.5f;

        GUI.Box(new Rect(boxX, boxY, boxWidth, boxHeight), "", style);

        // Event message
        GUIStyle textStyle = new GUIStyle(GUI.skin.label);
        textStyle.fontSize = 14;
        textStyle.wordWrap = true;
        textStyle.alignment = TextAnchor.MiddleCenter;
        textStyle.normal.textColor = Color.white;

        string displayText = currentMessage.message;
        if (currentMessage.requiresPlayerInput)
        {
            displayText += $"\n\n[Press {dismissKey} to continue]";
        }
        else
        {
            float timeLeft = currentMessage.displayTime - messageTimer;
            displayText += $"\n\n(Auto-dismiss in {timeLeft:F1}s)";
        }

        GUI.Label(new Rect(boxX + 10, boxY + 10, boxWidth - 20, boxHeight - 20), displayText, textStyle);
    }
}
