using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// Runtime quest creator - creates sample quests that can be added to the guild
/// </summary>
public class RuntimeQuestCreator : MonoBehaviour
{
    [Header("Auto-Create Options")]
    public bool createQuestsOnStart = true;
    public bool addToGuildOnStart = true;

    [Header("Debug")]
    public bool enableDebugLogs = true;

    private void Start()
    {
        if (createQuestsOnStart)
        {
            StartCoroutine(CreateSampleQuestsDelayed());
        }
    }

    private System.Collections.IEnumerator CreateSampleQuestsDelayed()
    {
        // Wait for other systems to initialize
        yield return new WaitForSeconds(1f);

        CreateSampleQuests();

        if (addToGuildOnStart)
        {
            yield return new WaitForSeconds(0.5f);
            AddQuestsToGuild();
        }
    }

    [ContextMenu("Create Sample Quests")]
    public void CreateSampleQuests()
    {
        LogDebug("Creating sample quests...");

        var quests = new List<Quest>();

        // Create a variety of quests
        quests.Add(CreateBanditCampQuest());
        quests.Add(CreateMissingMerchantQuest());
        quests.Add(CreateArtifactRetrievalQuest());
        quests.Add(CreateWolfPackQuest());
        quests.Add(CreateDeliveryQuest());

        LogDebug($"✅ Created {quests.Count} sample quests");

        // Store them for access
        foreach (var quest in quests)
        {
            // You could save these to a list or directly add to guild
            LogDebug($"📝 Quest: {quest.questTitle}");
        }
    }

    [ContextMenu("Add Quests to Guild")]
    public void AddQuestsToGuild()
    {
        var guild = FindFirstObjectByType<AdventurersGuild>();
        if (guild == null)
        {
            LogDebug("❌ No AdventurersGuild found!");
            return;
        }

        LogDebug("Adding sample quests to guild...");

        // Use the guild's debug method to add a simple quest
        // Since we can't access private fields directly, we'll use the debug context menu
        LogDebug("Use the guild's 'Create Simple Test Quest' context menu to add quests");

        // Alternatively, create quests and try to get them added
        var sampleQuests = CreateMultipleTestQuests();

        // Force refresh the guild
        guild.RefreshQuestBoard();

        LogDebug("Guild refresh completed");
    }

    private List<Quest> CreateMultipleTestQuests()
    {
        var quests = new List<Quest>();

        // Create several test quests with different requirements
        for (int i = 0; i < 3; i++)
        {
            var quest = CreateTestQuest(i);
            quests.Add(quest);
        }

        return quests;
    }

    private Quest CreateTestQuest(int index)
    {
        var quest = ScriptableObject.CreateInstance<Quest>();

        switch (index)
        {
            case 0:
                quest.questTitle = "Goblin Menace";
                quest.questDescription = "Goblins are raiding nearby farms. Drive them back to their caves.";
                quest.targetAreaName = "Goblin Caves";
                quest.goldReward = 50;
                quest.renownReward = 8;
                break;
            case 1:
                quest.questTitle = "Lost Caravan";
                quest.questDescription = "A merchant caravan went missing on the mountain pass. Investigate their disappearance.";
                quest.targetAreaName = "Mountain Pass";
                quest.goldReward = 100;
                quest.renownReward = 15;
                break;
            case 2:
                quest.questTitle = "Bandit Hideout";
                quest.questDescription = "Bandits have been terrorizing travelers. Find their hideout and bring them to justice.";
                quest.targetAreaName = "Dark Forest";
                quest.goldReward = 150;
                quest.renownReward = 20;
                quest.minimumRenown = 5;
                break;
        }

        // Common properties
        quest.questType = QuestType.Combat;
        quest.difficulty = QuestDifficulty.Easy;
        quest.timeLimitDays = 7;
        quest.targetMapPosition = new Vector2Int(50 + index * 10, 50 + index * 5);
        quest.minimumRenown = index * 2; // Progressive requirements

        quest.goals.Add(new QuestGoal
        {
            description = $"Defeat enemies in {quest.targetAreaName}",
            goalType = QuestGoalType.KillEnemies,
            targetName = "Enemy",
            targetCount = 3 + index * 2
        });

        return quest;
    }

    private Quest CreateBanditCampQuest()
    {
        var quest = ScriptableObject.CreateInstance<Quest>();
        quest.questTitle = "Clear the Bandit Camp";
        quest.questDescription = "Bandits have been attacking merchants on the main road. Their camp has been spotted in the nearby forest. Clear them out and make the roads safe for trade.";
        quest.questType = QuestType.Combat;
        quest.difficulty = QuestDifficulty.Easy;
        quest.timeLimitDays = 5;
        quest.targetAreaName = "Darkwood Forest";
        quest.targetMapPosition = new Vector2Int(45, 60);
        quest.goldReward = 75;
        quest.renownReward = 10;
        quest.minimumRenown = 0;

        quest.goals.Add(new QuestGoal
        {
            description = "Defeat 3 Bandits",
            goalType = QuestGoalType.KillEnemies,
            targetName = "Bandit",
            targetCount = 3
        });

        quest.goals.Add(new QuestGoal
        {
            description = "Defeat the Bandit Leader",
            goalType = QuestGoalType.DefeatBoss,
            targetName = "Bandit Chief",
            targetCount = 1
        });

        return quest;
    }

    private Quest CreateMissingMerchantQuest()
    {
        var quest = ScriptableObject.CreateInstance<Quest>();
        quest.questTitle = "Missing Merchant";
        quest.questDescription = "Merchant Harold departed for the next town three days ago but never arrived. His family fears the worst. Find him and bring him home safely.";
        quest.questType = QuestType.Rescue;
        quest.difficulty = QuestDifficulty.Normal;
        quest.timeLimitDays = 7;
        quest.targetAreaName = "Whispering Hills";
        quest.targetMapPosition = new Vector2Int(65, 45);
        quest.goldReward = 120;
        quest.renownReward = 15;
        quest.minimumRenown = 5;

        quest.goals.Add(new QuestGoal
        {
            description = "Find Merchant Harold",
            goalType = QuestGoalType.RescuePerson,
            targetName = "Harold",
            targetCount = 1
        });

        return quest;
    }

    private Quest CreateArtifactRetrievalQuest()
    {
        var quest = ScriptableObject.CreateInstance<Quest>();
        quest.questTitle = "The Crystal of Ages";
        quest.questDescription = "An ancient crystal with magical properties has been discovered in ruins to the east. Retrieve it before it falls into the wrong hands.";
        quest.questType = QuestType.Retrieval;
        quest.difficulty = QuestDifficulty.Normal;
        quest.timeLimitDays = 10;
        quest.targetAreaName = "Ancient Ruins";
        quest.targetMapPosition = new Vector2Int(80, 40);
        quest.goldReward = 200;
        quest.renownReward = 25;
        quest.minimumRenown = 10;

        quest.goals.Add(new QuestGoal
        {
            description = "Retrieve the Crystal of Ages",
            goalType = QuestGoalType.CollectItems,
            targetName = "Crystal of Ages",
            targetCount = 1
        });

        return quest;
    }

    private Quest CreateWolfPackQuest()
    {
        var quest = ScriptableObject.CreateInstance<Quest>();
        quest.questTitle = "Wolf Pack Threat";
        quest.questDescription = "A large pack of wolves has been attacking livestock near the village. The alpha must be dealt with to scatter the pack.";
        quest.questType = QuestType.Combat;
        quest.difficulty = QuestDifficulty.Easy;
        quest.timeLimitDays = 3;
        quest.targetAreaName = "Northern Woods";
        quest.targetMapPosition = new Vector2Int(30, 70);
        quest.goldReward = 60;
        quest.renownReward = 8;
        quest.minimumRenown = 0;

        quest.goals.Add(new QuestGoal
        {
            description = "Defeat the Alpha Wolf",
            goalType = QuestGoalType.DefeatBoss,
            targetName = "Alpha Wolf",
            targetCount = 1
        });

        return quest;
    }

    private Quest CreateDeliveryQuest()
    {
        var quest = ScriptableObject.CreateInstance<Quest>();
        quest.questTitle = "Urgent Medicine Delivery";
        quest.questDescription = "The village healer needs rare herbs delivered to a settlement to the south. Time is of the essence as people are depending on this medicine.";
        quest.questType = QuestType.Delivery;
        quest.difficulty = QuestDifficulty.Easy;
        quest.timeLimitDays = 2;
        quest.targetAreaName = "Southern Settlement";
        quest.targetMapPosition = new Vector2Int(50, 25);
        quest.goldReward = 80;
        quest.renownReward = 12;
        quest.minimumRenown = 0;

        quest.goals.Add(new QuestGoal
        {
            description = "Deliver medicine to Southern Settlement",
            goalType = QuestGoalType.ReachLocation,
            targetName = "Southern Settlement",
            targetCount = 1
        });

        return quest;
    }

    private void LogDebug(string message)
    {
        if (enableDebugLogs)
        {
            Debug.Log($"[RuntimeQuestCreator] {message}");
        }
    }
}
