using UnityEngine;

/// <summary>
/// Quick fix to properly setup SettlementInteractionManager references
/// Run this in play mode to fix the settlement interaction system
/// </summary>
public class SettlementInteractionFixer : MonoBehaviour
{
    [Header("Fix Settlement Interaction")]
    [Space]
    [TextArea(3, 5)]
    public string instructions = "1. Run this in Play Mode\n2. Click 'Fix Settlement Interaction' button\n3. Move TeamMarker near settlements\n4. Press E to enter";

    [ContextMenu("Fix Settlement Interaction")]
    public void FixSettlementInteraction()
    {
        Debug.Log("=== Fixing Settlement Interaction ===");

        // Find components
        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
        var teamMarker = GameObject.Find("TeamMarker");
        var mapMaker = FindFirstObjectByType<MapMaker2>();

        if (settlementManager == null)
        {
            Debug.LogError("❌ SettlementInteractionManager not found! Create it first.");
            return;
        }

        // Fix TeamMarker reference
        if (teamMarker != null)
        {
            settlementManager.SetTeamMarker(teamMarker.transform);
            Debug.Log("✅ TeamMarker reference set");
        }
        else
        {
            Debug.LogError("❌ TeamMarker GameObject not found!");
        }

        // Check MapMaker2 and MapData
        if (mapMaker != null)
        {
            var mapData = mapMaker.GetMapData();
            if (mapData != null)
            {
                var settlements = mapData.GetAllSettlements();
                Debug.Log($"✅ MapData found with {settlements?.Count ?? 0} settlements");
            }
            else
            {
                Debug.LogError("❌ MapData is null!");
            }
        }
        else
        {
            Debug.LogError("❌ MapMaker2 not found!");
        }

        // Test current position
        if (teamMarker != null)
        {
            Vector3 teamPos = teamMarker.transform.position;
            Debug.Log($"📍 TeamMarker position: {teamPos}");

            // Force check for nearby settlements
            var currentSettlement = settlementManager.GetCurrentNearbySettlement();
            Debug.Log($"🏠 Current nearby settlement: {(currentSettlement?.name ?? "None")}");
        }

        Debug.Log("=== Fix Complete ===");
        Debug.Log("Now move TeamMarker near a settlement and press E");
    }

    [ContextMenu("Test Settlement Detection")]
    public void TestSettlementDetection()
    {
        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
        var teamMarker = GameObject.Find("TeamMarker");
        var mapMaker = FindFirstObjectByType<MapMaker2>();

        if (settlementManager == null || teamMarker == null || mapMaker == null)
        {
            Debug.LogError("Missing components for testing!");
            return;
        }

        Vector2 teamWorldPos = new Vector2(teamMarker.transform.position.x, teamMarker.transform.position.z);
        Debug.Log($"🎯 TeamMarker world position: {teamWorldPos}");

        // Convert to map coordinates manually to check conversion
        float tileSize = 1f;
        var mapVisualizer = FindFirstObjectByType<MapVisualizer>();
        if (mapVisualizer != null && mapVisualizer.tileSize > 0)
        {
            tileSize = mapVisualizer.tileSize;
            Debug.Log($"📏 MapVisualizer tile size: {tileSize}");
        }
        else
        {
            Debug.LogWarning("⚠️ MapVisualizer not found, using default tile size 1.0");
        }

        Vector2Int mapPos = new Vector2Int(
            Mathf.RoundToInt(teamWorldPos.x / tileSize),
            Mathf.RoundToInt(teamWorldPos.y / tileSize)
        );
        Debug.Log($"🗺️ Converted map position: {mapPos}");

        // Test different coordinate interpretations
        Vector2Int mapPosFloor = new Vector2Int(
            Mathf.FloorToInt(teamWorldPos.x / tileSize),
            Mathf.FloorToInt(teamWorldPos.y / tileSize)
        );
        Vector2Int mapPosCeil = new Vector2Int(
            Mathf.CeilToInt(teamWorldPos.x / tileSize),
            Mathf.CeilToInt(teamWorldPos.y / tileSize)
        );
        Debug.Log($"🔍 Alternative positions - Floor: {mapPosFloor}, Ceil: {mapPosCeil}");

        // Check settlements manually
        var mapData = mapMaker.GetMapData();
        if (mapData != null)
        {
            var settlements = mapData.GetAllSettlements();
            Debug.Log($"📊 Total settlements: {settlements?.Count ?? 0}");

            if (settlements != null)
            {
                Debug.Log("🏘️ Checking all settlements:");
                foreach (var settlement in settlements)
                {
                    float distanceRound = Vector2Int.Distance(mapPos, settlement.position);
                    float distanceFloor = Vector2Int.Distance(mapPosFloor, settlement.position);
                    float distanceCeil = Vector2Int.Distance(mapPosCeil, settlement.position);

                    Debug.Log($"   '{settlement.name}' at {settlement.position}");
                    Debug.Log($"     Round distance: {distanceRound:F2}");
                    Debug.Log($"     Floor distance: {distanceFloor:F2}");
                    Debug.Log($"     Ceil distance: {distanceCeil:F2}");

                    if (distanceRound <= 2f || distanceFloor <= 2f || distanceCeil <= 2f)
                    {
                        Debug.Log($"🎯 WITHIN RANGE: {settlement.name}");

                        // Test the exact method SettlementInteractionManager uses
                        var foundSettlement = mapData.GetSettlementAt(mapPos, 2f);
                        Debug.Log($"🔍 GetSettlementAt result: {foundSettlement?.name ?? "null"}");
                    }
                }

                // Try to find settlements around the exact position (122, 71)
                Debug.Log($"🔍 Checking exact position (122, 71):");
                var exactSettlement = mapData.GetSettlementAt(new Vector2Int(122, 71), 2f);
                Debug.Log($"   Settlement at (122, 71): {exactSettlement?.name ?? "None"}");
            }
        }
    }

    [ContextMenu("Force Manual Entry")]
    public void ForceManualEntry()
    {
        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
        if (settlementManager != null)
        {
            settlementManager.TestEnterCurrentSettlement();
        }
        else
        {
            Debug.LogError("SettlementInteractionManager not found!");
        }
    }

    void Update()
    {
        // Show debug info on screen
        if (Input.GetKeyDown(KeyCode.F9))
        {
            FixSettlementInteraction();
        }

        if (Input.GetKeyDown(KeyCode.F10))
        {
            TestSettlementDetection();
        }

        if (Input.GetKeyDown(KeyCode.F11))
        {
            ForceManualEntry();
        }
    }

    void OnGUI()
    {
        GUILayout.BeginArea(new Rect(10, Screen.height - 150, 400, 140));
        GUILayout.BeginVertical("box");

        GUILayout.Label("Settlement Interaction Quick Fix", new GUIStyle(GUI.skin.label) { fontSize = 14, fontStyle = FontStyle.Bold });

        if (GUILayout.Button("Fix Settlement Interaction (F9)"))
        {
            FixSettlementInteraction();
        }

        if (GUILayout.Button("Test Settlement Detection (F10)"))
        {
            TestSettlementDetection();
        }

        if (GUILayout.Button("Force Manual Entry (F11)"))
        {
            ForceManualEntry();
        }

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
}
