using UnityEngine;

namespace Quests
{
    public class Q2SweepDirtQuest : MonoBehaviour, IQuest
    {
        [Header("Quest Settings")]
        [SerializeField] private string questName = "Уборка помещений";
        [SerializeField] private int dirtPilesTotal = 5;
        [SerializeField] private ItemData broomItem;

        [Header("Target Tags")]
        [SerializeField] private string broomGiverTag = "BroomLocation"; // Тэг места, где стоит метла
        [SerializeField] private string dirtTag = "Dirt";                // Тэг самой грязи

        private enum Stage
        {
            NotStarted,
            FindBroom,
            SweepDirt,
            Completed
        }

        private Stage currentStage = Stage.NotStarted;
        private int cleanedDirtCount = 0;

        public string QuestName => questName;
        public string Description { get; private set; }
        public int CurrentStep => cleanedDirtCount;
        public int TotalSteps => dirtPilesTotal;
        public bool IsCompleted => currentStage == Stage.Completed;

        public event System.Action<string> OnQuestStepChanged;

        public void StartQuest()
        {
            if (broomItem == null) Debug.LogError($"[Q2] Broom ItemData is missing!");

            currentStage = Stage.FindBroom;
            cleanedDirtCount = 0;

            // Скрываем руки (убираем мусорный мешок из прошлого квеста)
            PlayerHandsController.Instance?.HideHands();

            if (InteractionHandler.Instance != null)
            {
                InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
            }
            UpdateQuestState();
        }

        private void OnDestroy()
        {
            if (InteractionHandler.Instance != null)
            {
                InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
            }
        }

        private void HandleInteraction(GameObject obj)
        {
            if (currentStage == Stage.Completed || obj == null) return;

            switch (currentStage)
            {
                case Stage.FindBroom:
                    // Если игрок взаимодействовал с объектом метлы (поднял её)
                    if (obj.CompareTag(broomGiverTag))
                    {
                        currentStage = Stage.SweepDirt;
                        
                        // Показываем визуальную метлу в руках
                        PlayerHandsController.Instance?.ShowBroom(true);
                        
                        UpdateQuestState();
                    }
                    break;

                case Stage.SweepDirt:
                    // Если игрок взаимодействовал с грязью
                    if (obj.CompareTag(dirtTag))
                    {
                        cleanedDirtCount++;
                        QuestManager.Instance.StepCompleted();

                        if (cleanedDirtCount >= dirtPilesTotal)
                        {
                            FinishQuest();
                        }
                        else
                        {
                            UpdateQuestState();
                        }
                    }
                    break;
            }
        }

        private void UpdateQuestState()
        {
            switch (currentStage)
            {
                case Stage.FindBroom:
                    Description = "Найдите метлу.";
                    break;
                case Stage.SweepDirt:
                    Description = $"Подметите пол в комнатах: {cleanedDirtCount} / {dirtPilesTotal}";
                    break;
                case Stage.Completed:
                    Description = "Пол чист!";
                    break;
            }
            OnQuestStepChanged?.Invoke(Description);
        }

        private void FinishQuest()
        {
            currentStage = Stage.Completed;
            
            // Прячем метлу по завершении
            PlayerHandsController.Instance?.ShowBroom(false); 
            // Или PlayerHandsController.Instance?.HideHands();
            
            UpdateQuestState();
            QuestManager.Instance.CompleteQuest();
        }

        public void AdvanceQuestStep() { }
        public void CompleteQuest() 
        {
             if (InteractionHandler.Instance != null)
            {
                InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
            }
             InventorySystem.Instance.RemoveItem(broomItem);
        }
    }
}