using UnityEngine;

/// <summary>
/// Setup script to easily add the Travel Event System to your existing travel setup
/// This component should be added to the same GameObject as TeamTravelSystem
/// </summary>
public class TravelEventSystemSetup : MonoBehaviour
{
    [Header("Event System Setup")]
    [Tooltip("Automatically create and configure the travel event system")]
    public bool autoSetupEventSystem = true;

    [Header("Event Configuration")]
    [Range(0f, 1f)]
    [Tooltip("Base chance for events to occur (15% recommended)")]
    public float eventChance = 0.15f;

    [Range(1, 10)]
    [Tooltip("Check for events every N tiles traveled")]
    public int tilesPerCheck = 3;

    [Tooltip("Enable debug logging for events")]
    public bool enableDebugLogs = true;

    [Header("Default Events")]
    [Tooltip("Create default ScriptableObject events automatically")]
    public bool createDefaultEvents = true;

    void Start()
    {
        if (autoSetupEventSystem)
        {
            SetupEventSystem();
        }
    }

    [ContextMenu("Setup Event System")]
    public void SetupEventSystem()
    {
        // Check if TravelEventSystem already exists
        TravelEventSystem existingSystem = GetComponent<TravelEventSystem>();
        if (existingSystem != null)
        {
            Debug.Log("✅ TravelEventSystem already exists on this GameObject");
            ConfigureExistingSystem(existingSystem);
            return;
        }

        // Add TravelEventSystem component
        TravelEventSystem eventSystem = gameObject.AddComponent<TravelEventSystem>();

        // Configure the system
        eventSystem.enableEvents = true;
        eventSystem.baseEventChance = eventChance;
        eventSystem.tilesPerEventCheck = tilesPerCheck;
        eventSystem.showDebugLogs = enableDebugLogs;

        Debug.Log("✅ TravelEventSystem added and configured");

        // Create default events if requested
        if (createDefaultEvents)
        {
            CreateDefaultEventAssets();
        }

        // Verify integration
        VerifyIntegration();
    }

    private void ConfigureExistingSystem(TravelEventSystem eventSystem)
    {
        eventSystem.baseEventChance = eventChance;
        eventSystem.tilesPerEventCheck = tilesPerCheck;
        eventSystem.showDebugLogs = enableDebugLogs;

        Debug.Log("🔧 Updated existing TravelEventSystem configuration");
    }

    [ContextMenu("Create Default Events")]
    public void CreateDefaultEventAssets()
    {
        // This would create ScriptableObject assets in the Resources folder
        // For now, we'll just log what would be created

        string[] defaultEvents = {
            "Forest Ambush Event",
            "Mountain Ambush Event",
            "Traveling Merchant Event",
            "Road Patrol Event",
            "Hidden Cache Event",
            "Wild Animal Event",
            "Rest Site Event",
            "Weather Hazard Event"
        };

        Debug.Log("📦 Default events that should be created:");
        foreach (string eventName in defaultEvents)
        {
            Debug.Log($"   - {eventName}");
        }

        Debug.Log("💡 To create these events:");
        Debug.Log("   1. Right-click in Project window");
        Debug.Log("   2. Go to Create > RPG > Travel Events");
        Debug.Log("   3. Choose the event type you want");
        Debug.Log("   4. Configure the event settings");
        Debug.Log("   5. Add to the Available Events list in TravelEventSystem");
    }

    private void VerifyIntegration()
    {
        Debug.Log("🔍 Verifying Travel Event System Integration...");

        // Check for required components
        TeamTravelSystem travelSystem = GetComponent<TeamTravelSystem>();
        if (travelSystem == null)
        {
            Debug.LogError("❌ TeamTravelSystem not found! TravelEventSystem requires TeamTravelSystem on the same GameObject.");
            return;
        }

        SimpleTeamPlacement teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        if (teamPlacement == null)
        {
            Debug.LogWarning("⚠️ SimpleTeamPlacement not found in scene. Events may not work properly.");
        }

        MapMaker2 mapMaker = FindFirstObjectByType<MapMaker2>();
        if (mapMaker == null)
        {
            Debug.LogWarning("⚠️ MapMaker2 not found in scene. Events may not work properly.");
        }

        TravelEventSystem eventSystem = GetComponent<TravelEventSystem>();
        if (eventSystem != null && eventSystem.availableEvents.Count == 0)
        {
            Debug.LogWarning("⚠️ No events assigned to TravelEventSystem. Create and assign travel events for the system to work.");
        }

        Debug.Log("✅ Integration verification complete");
    }

    [ContextMenu("Test Event System")]
    public void TestEventSystem()
    {
        TravelEventSystem eventSystem = GetComponent<TravelEventSystem>();
        if (eventSystem == null)
        {
            Debug.LogError("❌ No TravelEventSystem found. Run Setup Event System first.");
            return;
        }

        Debug.Log("🎲 Testing travel event system...");
        eventSystem.TriggerEventCheck();
    }

    void OnValidate()
    {
        // Clamp values
        eventChance = Mathf.Clamp01(eventChance);
        tilesPerCheck = Mathf.Clamp(tilesPerCheck, 1, 10);
    }
}

/// <summary>
/// Helper script to create example travel events for testing
/// Add this to any GameObject to quickly create test events
/// </summary>
public class TravelEventExampleCreator : MonoBehaviour
{
    [ContextMenu("Create Example Events")]
    public void CreateExampleEvents()
    {
        Debug.Log("🎭 Creating example travel events...");

        // This demonstrates how to create events at runtime for testing
        CreateExampleAmbushEvent();
        CreateExampleMerchantEvent();
        CreateExampleDiscoveryEvent();

        Debug.Log("✅ Example events created. Check the TravelEventSystem component.");
    }

    private void CreateExampleAmbushEvent()
    {
        var ambushEvent = ScriptableObject.CreateInstance<CombatTravelEvent>();
        ambushEvent.eventName = "Test Forest Ambush";
        ambushEvent.eventDescription = "A test ambush event for debugging";
        ambushEvent.eventType = EventType.Combat;
        ambushEvent.rarity = EventRarity.Common;

        // Set terrain preferences
        ambushEvent.forestChance = 0.9f;
        ambushEvent.roadChance = 0.2f;
        ambushEvent.townChance = 0.1f;

        // Add to event system if available
        TravelEventSystem eventSystem = FindFirstObjectByType<TravelEventSystem>();
        if (eventSystem != null)
        {
            eventSystem.availableEvents.Add(ambushEvent);
            Debug.Log("➕ Added test ambush event");
        }
    }

    private void CreateExampleMerchantEvent()
    {
        var merchantEvent = ScriptableObject.CreateInstance<TradingTravelEvent>();
        merchantEvent.eventName = "Test Traveling Merchant";
        merchantEvent.eventDescription = "A test merchant event for debugging";
        merchantEvent.eventType = EventType.Trading;
        merchantEvent.rarity = EventRarity.Common;

        // Set terrain preferences
        merchantEvent.roadChance = 0.8f;
        merchantEvent.townChance = 0.7f;
        merchantEvent.forestChance = 0.3f;

        // Add to event system if available
        TravelEventSystem eventSystem = FindFirstObjectByType<TravelEventSystem>();
        if (eventSystem != null)
        {
            eventSystem.availableEvents.Add(merchantEvent);
            Debug.Log("➕ Added test merchant event");
        }
    }

    private void CreateExampleDiscoveryEvent()
    {
        var discoveryEvent = ScriptableObject.CreateInstance<DiscoveryTravelEvent>();
        discoveryEvent.eventName = "Test Hidden Treasure";
        discoveryEvent.eventDescription = "A test discovery event for debugging";
        discoveryEvent.eventType = EventType.Discovery;
        discoveryEvent.rarity = EventRarity.Uncommon;

        // Set terrain preferences
        discoveryEvent.forestChance = 0.7f;
        discoveryEvent.mountainChance = 0.8f;
        discoveryEvent.roadChance = 0.2f;

        // Add to event system if available
        TravelEventSystem eventSystem = FindFirstObjectByType<TravelEventSystem>();
        if (eventSystem != null)
        {
            eventSystem.availableEvents.Add(discoveryEvent);
            Debug.Log("➕ Added test discovery event");
        }
    }
}
