using UnityEngine;
using System;

/// <summary>
/// Simple IMGUI-based action wheel that doesn't require any Canvas setup
/// Perfect for testing and prototyping the battle action system
/// </summary>
public class SimpleActionWheel : MonoBehaviour
{
    [Header("Settings")]
    public KeyCode toggleKey = KeyCode.Q;
    public bool showDebugGUI = true;

    private Character currentCharacter;
    private bool isVisible = false;
    private Vector2 wheelCenter;
    private float wheelRadius = 120f; // Increased for better spacing
    private float buttonSize = 70f; // Larger buttons for better visibility

    // Events
    public event Action<BattleActionType> OnActionSelected;

    private BattleActionType[] actionTypes =
    {
        BattleActionType.Attack,
        BattleActionType.Move,
        BattleActionType.UseItem,
        BattleActionType.CastSpell,
        BattleActionType.Defend,
        BattleActionType.RunAway
    };

    private string[] actionLabels =
    {
        "⚔️ Attack",
        "👟 Move",
        "🧪 Item",
        "✨ Spell",
        "🛡️ Defend",
        "💨 Run"
    };

    private Color[] actionColors =
    {
        Color.red,
        Color.green,
        Color.blue,
        Color.magenta,
        Color.yellow,
        Color.gray
    };

    void Update()
    {
        if (isVisible && Input.GetKeyDown(KeyCode.Escape))
        {
            HideWheel();
        }
    }

    void OnGUI()
    {
        if (!isVisible || currentCharacter == null) return;

        // Set up GUI
        GUI.depth = -1000; // Ensure it's on top

        // Draw background
        Vector2 center = new Vector2(Screen.width / 2, Screen.height / 2);
        wheelCenter = center;

        // Draw wheel background with better visibility
        DrawCircle(center, wheelRadius + 30, new Color(0, 0, 0, 0.8f)); // Darker background
        DrawCircle(center, wheelRadius + 25, Color.white);
        DrawCircle(center, wheelRadius + 20, new Color(0.2f, 0.2f, 0.2f, 0.9f)); // Inner background

        // Draw title with better contrast and auto-sizing
        GUI.color = Color.white;
        GUIStyle titleStyle = new GUIStyle(GUI.skin.label);
        titleStyle.fontSize = 24; // Starting font size
        titleStyle.alignment = TextAnchor.MiddleCenter;
        titleStyle.normal.textColor = Color.white;
        titleStyle.fontStyle = FontStyle.Bold;

        string titleText = $"{currentCharacter.CharacterName} - Choose Action";
        Rect titleRect = new Rect(center.x - 200, center.y - wheelRadius - 60, 400, 40);

        // Auto-size text to fit the available width
        Vector2 textSize = titleStyle.CalcSize(new GUIContent(titleText));
        if (textSize.x > titleRect.width)
        {
            // Calculate scale factor to fit text
            float scaleFactor = titleRect.width / textSize.x;
            titleStyle.fontSize = Mathf.Max(14, Mathf.RoundToInt(titleStyle.fontSize * scaleFactor));
        }

        // Draw background for title text
        GUI.color = new Color(0, 0, 0, 0.8f);
        GUI.Box(titleRect, "");

        GUI.color = Color.white;
        GUI.Label(titleRect, titleText, titleStyle);

        // Draw action buttons with better spacing
        int actionCount = actionTypes.Length;
        float angleStep = 360f / actionCount;

        for (int i = 0; i < actionCount; i++)
        {
            float angle = i * angleStep - 90f; // Start from top
            Vector2 buttonPos = GetPositionOnCircle(center, angle, wheelRadius * 0.75f); // Moved closer to center

            DrawActionButton(buttonPos, actionTypes[i], actionLabels[i], actionColors[i]);
        }

        // Draw improved instructions
        GUIStyle instructionStyle = new GUIStyle(GUI.skin.label);
        instructionStyle.fontSize = 16;
        instructionStyle.alignment = TextAnchor.MiddleCenter;
        instructionStyle.normal.textColor = Color.white;
        instructionStyle.fontStyle = FontStyle.Bold;

        Rect instructionRect = new Rect(center.x - 250, center.y + wheelRadius + 40, 500, 25);

        // Background for instructions
        GUI.color = new Color(0, 0, 0, 0.8f);
        GUI.Box(instructionRect, "");

        GUI.color = Color.white;
        GUI.Label(instructionRect, "Click action, ESC to cancel, or Q to change action later", instructionStyle);

        GUI.color = Color.white;
    }

    private void DrawActionButton(Vector2 position, BattleActionType actionType, string label, Color color)
    {
        Rect buttonRect = new Rect(position.x - buttonSize / 2, position.y - buttonSize / 2, buttonSize, buttonSize);

        // Check if mouse is over button
        bool isHovered = buttonRect.Contains(Event.current.mousePosition);

        // Draw button with improved visuals
        Color buttonColor = isHovered ? Color.Lerp(color, Color.white, 0.4f) : color;

        // Draw button shadow
        GUI.color = new Color(0, 0, 0, 0.5f);
        Rect shadowRect = new Rect(buttonRect.x + 3, buttonRect.y + 3, buttonRect.width, buttonRect.height);
        GUI.Box(shadowRect, "");

        // Draw button background
        GUI.color = buttonColor;
        GUI.Box(buttonRect, "");

        // Draw button border (simple outline)
        GUI.color = isHovered ? Color.white : new Color(0.8f, 0.8f, 0.8f);
        GUI.Box(new Rect(buttonRect.x - 1, buttonRect.y - 1, buttonRect.width + 2, buttonRect.height + 2), "");

        // Draw button text
        GUIStyle buttonStyle = new GUIStyle(GUI.skin.label);
        buttonStyle.fontSize = 14;
        buttonStyle.alignment = TextAnchor.MiddleCenter;
        buttonStyle.normal.textColor = isHovered ? Color.black : Color.white;
        buttonStyle.fontStyle = FontStyle.Bold;
        buttonStyle.wordWrap = true;

        GUI.color = Color.white;
        GUI.Label(buttonRect, label, buttonStyle);

        // Handle button click using GUI.Button for easier event handling
        GUI.color = Color.clear; // Make button invisible
        if (GUI.Button(buttonRect, "", GUIStyle.none))
        {
            OnActionButtonClicked(actionType);
        }

        GUI.color = Color.white;
    }

    private void DrawCircle(Vector2 center, float radius, Color color)
    {
        GUI.color = color;
        float size = radius * 2;
        Rect circleRect = new Rect(center.x - radius, center.y - radius, size, size);

        // Simple circle approximation using GUI.DrawTexture with a circular texture
        // For simplicity, we'll just draw a square for now
        GUI.Box(circleRect, "");
        GUI.color = Color.white;
    }

    private Vector2 GetPositionOnCircle(Vector2 center, float angle, float radius)
    {
        float radian = angle * Mathf.Deg2Rad;
        float x = center.x + Mathf.Cos(radian) * radius;
        float y = center.y + Mathf.Sin(radian) * radius;
        return new Vector2(x, y);
    }

    private void OnActionButtonClicked(BattleActionType actionType)
    {
        Debug.Log($"🎯 Action button clicked: {actionType}");
        Debug.Log($"🎯 OnActionSelected event has {(OnActionSelected != null ? OnActionSelected.GetInvocationList().Length : 0)} subscribers");

        OnActionSelected?.Invoke(actionType);

        Debug.Log($"🎯 Event invoked, hiding wheel...");
        HideWheel();
    }

    public void ShowWheelForCharacter(Character character)
    {
        Debug.Log($"🎮 SimpleActionWheel.ShowWheelForCharacter called with: {(character != null ? character.CharacterName : "NULL")}");

        if (character == null)
        {
            Debug.LogWarning("Cannot show action wheel: character is null");
            return;
        }

        currentCharacter = character;
        isVisible = true;

        Debug.Log($"🎮 Simple action wheel shown for {character.CharacterName} - isVisible: {isVisible}");
    }
    public void HideWheel()
    {
        isVisible = false;
        currentCharacter = null;

        Debug.Log("🎮 Simple action wheel hidden");
    }

    private Character FindSelectedCharacter()
    {
        // Find the currently selected character
        var characters = FindObjectsByType<Character>(FindObjectsSortMode.None);

        foreach (var character in characters)
        {
            if (character.CompareTag("Player"))
            {
                // For now, return the first player character found
                // In a real implementation, you'd check which one is actually selected
                return character;
            }
        }

        return null;
    }

    void OnDestroy()
    {
        OnActionSelected = null;
    }
}
