using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DialogueSystem;
using UnityEngine;
using Hazards;
using Managers;
using UniRx;

public class GrandmaAI : UtilityAI
{
    // Interactable Encounter System
    private const float interactableTolerance = 2f;
    private bool isResolvingInteractable = false;
    // last advertiser associated with the seen interactable (used to verify we're resolving the correct target)

    // Final action
    public bool finalActionTriggered = false;
    public ActionAdvertiser finalActionAdvertiser;
    [Header("Final Action Level 3")]
    
    public LayerMask resolveLayerMask;
    
    public UIManager uiManager;

    public BoolReactiveProperty resolveBanana = new BoolReactiveProperty(false);
    
    protected override void OnUpdateExtra()
    {
        // Check whether the queued interactable should now be resolved
        HandleInteractableResolution();
        RefreshUI();
    }

    protected override void OnReachedTarget()
    {
        var adv = currentAction.advertiser;

        if (adv != null && adv.name == "Couch")
        {
            if (TvHandler.Instance && !TvHandler.Instance.PlayRandomChannel())
            {
                // TV is broken
                HUDManager.Instance.AddHealth(-1);
                Debug.Log("TV is broken! Grandma loses health.");
            }
        }

        if (adv.actionName == "Cooking")
        {
            AudioManager.Instance.PlayStove();
        }

        if (adv.actionName == "Toilet")
        {
            AudioManager.Instance.PlayToilet();
        }

        if (adv.actionName == "Bathtub")
        {
            AudioManager.Instance.PlayBathtub();
        }
        
        if (adv.actionName == "Bed" && finalActionTriggered)
        {
            if(HandleLevelCompletion.Instance)
            {
                HandleLevelCompletion.Instance.LevelWon();
                GlobalData.SaveData();
            }
            uiManager.ShowWin();
            Debug.Log("Grandma reached bed → WIN!");
        }

        if (finalActionTriggered && currentAction.advertiser == finalActionAdvertiser && finalActionAdvertiser.actionName == "Painting")
        {
            AudioManager.Instance.musicSource.Stop();
            OutroDialogue.Instance.StartOutroDialogue();
            GetComponent<Animator>().enabled = false;
            GetComponent<GrandmaAI>().enabled = false;
            GetComponent<GrandmaMovement>().enabled = false;
        }
        
        base.OnReachedTarget();
    }

    protected override void OnActionCompleted(GrandmaAction action)
    {
        // Cache old path and completed action for hazard spawning
        if (SpawnHazards.Instance)
        {
            Debug.Log($"SpawnHazards.Instance: {SpawnHazards.Instance}");
            SpawnHazards.Instance.CacheOldPath(movement.currentPath);
            SpawnHazards.Instance.CacheOldAction(action.advertiser);
        }
        // Reset ActionProgress when done
        ActionProgress.Instance.SetInProgress(false);
        ActionProgress.Instance.ResetProgressAmount();
    }

    private void HandleInteractableResolution()
    {
        if (isResolvingInteractable || currentAction == null)
            return;

        if (!currentAction.fixedTargetPosition.HasValue)
            return;

        float dist = Vector3.Distance(transform.position, currentAction.fixedTargetPosition.Value);

        if (dist <= interactableTolerance)
        {
            Debug.Log("Grandma is in the DISTANCE of an interactable, beginning resolving an interactable...");
            StartCoroutine(ResolveInteractable());
        }
    }
    
    private IEnumerator ResolveInteractable()
    {
        
        isResolvingInteractable = true;
        isWaiting = true;
        
        // Short delay to simulate interaction time
        yield return new WaitForSeconds(2f);
        bool found = false;

        Vector3 targetPos = currentAction.fixedTargetPosition.Value;

        var hits = Physics2D.OverlapCircleAll(targetPos, interactableTolerance, resolveLayerMask);
        foreach (var hit in hits)
        {
            
            if (hit && hit.CompareTag("Interactable") || hit.CompareTag("Fire"))
            {
                Debug.Log($"INTERACTABLE FOUND! Resolved interactable at {hit.transform.position}, tag: {hit.tag}");
                found = true;
                
                Destroy(hit.gameObject);

                if (hit.gameObject.GetComponent<ActionAdvertiser>()?.actionName == "Banana")
                {
                    resolveBanana.Value = true;
                }
                
                if (hit.gameObject.GetComponent<ActionAdvertiser>()?.actionName == "DeadCat")
                {
                    Debug.Log("Grandma found a dead cat! She loses more health.");
                    HUDManager.Instance.AddHealth(-2);
                    break;
                } else
                {
                    HUDManager.Instance.AddHealth(-1);
                    break;
                }
                
            }
        }
        if (!found)
        {
            Debug.Log("No interactable found at the expected position. Grandma loses sanity.");
            HUDManager.Instance.AddSanity(-1);
        }
        isResolvingInteractable = false;
        isWaiting = false;
        currentAction = null;
        RefreshUI();
    }

    public void TriggerFinalAction()
    {
        Debug.Log("Trigger Final Action");
        // Clear all actions and force final "go to bed" action
        ClearActions();
        actionQueue.Enqueue(new GrandmaAction(finalActionAdvertiser, 999f));
        finalActionTriggered = true;
        RefreshUI();
        showActionProgress = false;
    }

    
    public void NotifyInteractableSeen(Vector3 pos, ActionAdvertiser advertiser)
    {
        // Prevent duplicate instance
        if ((currentAction != null && currentAction.advertiser == advertiser) ||
            actionQueue.Any(a => a.advertiser == advertiser))
            return;

        bool isFire = advertiser.actionName == "Fire";

        // 🔥 check if ANY fire already exists (current or queued)
        bool fireAlreadyPresent =
            (currentAction != null && currentAction.advertiser.actionName == "Fire") ||
            actionQueue.Any(a => a.advertiser.actionName == "Fire");

        if (isFire && !fireAlreadyPresent)
        {
            // first fire only
            ClearActions();
            HUDManager.Instance.grandmaReaction.ShowExclamation();
        }

        if (advertiser.actionName == "DeadCat")
        {
            ClearActions();
            HUDManager.Instance.AddSanity(-1);
        }

        actionQueue.Enqueue(
            new GrandmaAction(advertiser, 900f, pos)
        );

        RefreshUI();
    }
    
    private void RefreshUI()
    {
        UIActionQueueDisplay.Instance.RefreshUI(actionQueue, currentAction);
    }
}
