using UnityEngine;
using System.Collections.Generic;
using System.Linq;

public class QuestManager : MonoBehaviour
{
    public static QuestManager Instance;

    [SerializeField] private List<GameObject> questPrefabs;
    private List<IQuest> allQuests = new List<IQuest>();

    private IQuest _currentQuest;
    public IQuest currentQuest => _currentQuest;

    public bool isStarted;

    public event System.Action<IQuest> OnQuestStarted;
    public event System.Action<IQuest> OnQuestCompleted;
    public event System.Action<string> OnQuestStepChanged;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);

            foreach (var qObj in questPrefabs)
            {
                var q = qObj.GetComponent<IQuest>();
                if (q != null) allQuests.Add(q);
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }

    void Start()
    {
        if (isStarted) StartFirstQuest();
    }

    public void StartFirstQuest()
    {
        if (allQuests.Count > 0) StartQuest(allQuests[0]);
    }

    public void StartQuest(IQuest quest)
    {
        if (_currentQuest != null && !_currentQuest.IsCompleted)
        {
            Debug.Log($"[QuestManager] Quest '{_currentQuest.QuestName}' is not completed yet.");
            return;
        }

        _currentQuest = quest;
        _currentQuest.OnQuestStepChanged += HandleQuestStepChanged;
        _currentQuest.StartQuest();

        Debug.Log($"[QuestManager] Started quest: {quest.QuestName}");
        OnQuestStarted?.Invoke(_currentQuest);

        HandleQuestStepChanged(_currentQuest.Description);
    }

    public void CompleteQuest()
    {
        if (_currentQuest != null)
        {
            Debug.Log($"[QuestManager] Quest '{_currentQuest.QuestName}' COMPLETED!");
            _currentQuest.OnQuestStepChanged -= HandleQuestStepChanged;
            _currentQuest.CompleteQuest();
            OnQuestCompleted?.Invoke(_currentQuest);

            var completedQuest = _currentQuest;
            _currentQuest = null;

            int completedIndex = allQuests.IndexOf(completedQuest);
            if (completedIndex >= 0 && completedIndex + 1 < allQuests.Count)
            {
                StartQuest(allQuests[completedIndex + 1]);
            }
            else
            {
                Debug.Log("[QuestManager] All quests completed!");
            }
        }
    }

    public void AdvanceCurrentQuestStep()
    {
        if (_currentQuest != null)
        {
            _currentQuest.AdvanceQuestStep();
        }
    }

    public void StepCompleted()
    {
        if (_currentQuest != null)
        {
            _currentQuest.AdvanceQuestStep();
        }
    }

    private void HandleQuestStepChanged(string description)
    {
        OnQuestStepChanged?.Invoke(description);
    }
}