using Player;
using UnityEngine;

namespace Quests
{
    public class Q1CollectGarbageQuest : MonoBehaviour, IQuest
    {
        [Header("Quest Settings")]
        [SerializeField] private string questName = "Clean Up The Area";
        [SerializeField] private int trashItemsPerBag = 3;
        [SerializeField] private int bagsToDisposeTotal = 2;
        [SerializeField] private ItemData garbageBagItem;

        [Header("Звуки Квеста")]
        [SerializeField] private AudioClip pickupBagSound;
        [SerializeField] private AudioClip collectTrashSound;
        [SerializeField] private AudioClip disposeBagSound;
        private PlayerController _playerController;

        [Header("Target Tags")]
        [SerializeField] private string bagGiverTag = "TrashBagBox";
        [SerializeField] private string trashTag = "Trash";
        [SerializeField] private string dumpsterTag = "Dumpster";

        private enum Stage
        {
            NotStarted,
            FindBag,
            FillBag,
            DisposeBag,
            Completed
        }

        private Stage currentStage = Stage.NotStarted;
        private int currentTrashInBag = 0;
        private int disposedBagsCount = 0;

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

        public event System.Action<string> OnQuestStepChanged;

        public void StartQuest()
        {
            if (garbageBagItem == null)
            {
                Debug.LogError("[QUEST START CHECK] Reference to 'garbageBagItem' is NULL when the quest starts. Check the quest object's inspector on the scene!");
            }
            else
            {
                Debug.Log($"[QUEST START CHECK] Reference to 'garbageBagItem' is SET. Item: '{garbageBagItem.itemName}'.");
            }

            currentStage = Stage.FindBag;
            disposedBagsCount = 0;
            currentTrashInBag = 0;
            PlayerHandsController.Instance?.HideHands();
            if (InteractionHandler.Instance != null)
            {
                InteractionHandler.Instance.onObjectInteracted += HandleInteraction;
            }
            else
            {
                Debug.LogError("InteractionHandler not found! The quest will not work.");
            }
            _playerController = Object.FindFirstObjectByType<PlayerController>();
            UpdateQuestState();
        }

        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.FindBag:
                    if (obj.CompareTag(bagGiverTag))
                    {
                        currentStage = Stage.FillBag;
                        currentTrashInBag = 0;
                        PlayerHandsController.Instance?.ShowBag(false);
                        _playerController?.PlayOneShotSound(pickupBagSound);
                        UpdateQuestState();
                    }
                    break;

                case Stage.FillBag:
                    if (obj.CompareTag(trashTag))
                    {
                        currentTrashInBag++;
                        _playerController?.PlayOneShotSound(collectTrashSound);
                        if (currentTrashInBag >= trashItemsPerBag)
                        {
                            currentStage = Stage.DisposeBag;
                            PlayerHandsController.Instance?.ShowBag(true);
                        }
                        UpdateQuestState();
                    }
                    break;

                case Stage.DisposeBag:
                    if (obj.CompareTag(dumpsterTag))
                    {
                        if (garbageBagItem != null)
                        {
                            InventorySystem.Instance.RemoveItem(garbageBagItem);
                        }
                        else
                        {
                            Debug.LogError("ItemData for the garbage bag is not specified in the quest!");
                        }
                    
                        PlayerHandsController.Instance?.HideHands();
                        _playerController?.PlayOneShotSound(disposeBagSound);
                        disposedBagsCount++;
                        QuestManager.Instance.StepCompleted();

                        if (disposedBagsCount >= bagsToDisposeTotal)
                        {
                            FinishQuest();
                        }
                        else
                        {
                            currentStage = Stage.FindBag;
                            UpdateQuestState();
                        }
                    }
                    break;
            }
        }

        private void UpdateQuestState()
        {
            switch (currentStage)
            {
                case Stage.FindBag:
                    Description = "Find a roll of trash bags.";
                    break;
                case Stage.FillBag:
                    Description = $"Collect trash in the bag: {currentTrashInBag} / {trashItemsPerBag}";
                    break;
                case Stage.DisposeBag:
                    Description = "Dispose of the full bag in the dumpster.";
                    break;
                case Stage.Completed:
                    Description = "Clean-up complete!";
                    break;
            }
            OnQuestStepChanged?.Invoke(Description);
        }

        public void AdvanceQuestStep() { }

        public bool IsBagFull()
        {
            if (currentStage == Stage.DisposeBag) return true;
            if (currentStage == Stage.FillBag) return currentTrashInBag >= trashItemsPerBag;
            return false;
        }

        private void FinishQuest()
        {
            currentStage = Stage.Completed;
            UpdateQuestState();
            QuestManager.Instance.CompleteQuest();
        }

        public void CompleteQuest()
        {
            PlayerHandsController.Instance?.HideHands();
            if (InteractionHandler.Instance != null)
            {
                InteractionHandler.Instance.onObjectInteracted -= HandleInteraction;
            }

            if (!string.IsNullOrEmpty(bagGiverTag))
            {
                GameObject bagGiver = GameObject.FindGameObjectWithTag(bagGiverTag);
                if (bagGiver != null)
                {
                    Object.Destroy(bagGiver);
                    Debug.Log($"Quest '{QuestName}' completed. Bag source '{bagGiver.name}' destroyed.");
                }
                else
                {
                    Debug.LogWarning($"Quest '{QuestName}' completed, but could not find the bag source with tag '{bagGiverTag}'.");
                }
            }
        }
    }
}