using SpillMechanic;
using UnityEngine;

namespace Cat
{
    public class Litterbox : MonoBehaviour
    {
        [Header("State")]
        public bool IsClean = true;

        [Header("Sprites")]
        [SerializeField] private Sprite cleanSprite;
        [SerializeField] private Sprite dirtySprite;
        [SerializeField] private SpriteRenderer spriteRendererNoCat;

        [Header("Animation")]
        [SerializeField] private Animator animator;
        [SerializeField] private string useAnimationTrigger = "Use";
        [SerializeField] private GameObject boxNoCat;
        [SerializeField] private GameObject boxWithCat;
        [SerializeField] private GameObject cat;
        
        [Header("Cleaning")]
        [SerializeField] private GameObject waterSpillPrefab;

        private WaterSpill activeSpill;

        private void Awake()
        {
            UpdateVisual();
        }
    
        public void Use()
        {
            //animator.SetTrigger(useAnimationTrigger);
            
            if (IsClean)
            {
                Debug.Log("Litterbox was clean, now becomes dirty");
                IsClean = false;
                SpawnCleaningSpill();
            }

            UpdateVisual();
        }

        public void ShowCatInside(bool showCat)
        {
            boxWithCat.SetActive(showCat);
            cat.GetComponent<SpriteRenderer>().enabled = !showCat;
            boxNoCat.SetActive(!showCat);
        }
        
        // Cleaning spill logic
        private void SpawnCleaningSpill()
        {
            Debug.Log("Spawning cleaning spill for litterbox");
            if (activeSpill != null) return;

            Vector3 boxPos = boxNoCat.transform.position;
            
            GameObject waterSpill = Instantiate(
                waterSpillPrefab,
                new Vector3(boxPos.x, boxPos.y, -1),
                Quaternion.identity
            );

            activeSpill = waterSpill.GetComponent<WaterSpill>();

            // Hide spill sprite. Player cleans an invisible waterspill
            var waterRenderer = waterSpill.GetComponent<SpriteRenderer>();
            if (waterRenderer) waterRenderer.enabled = false;

            // When the spill is destroyed, litterbox becomes clean
            StartCoroutine(WaitForSpillRemoval());
        }

        private System.Collections.IEnumerator WaitForSpillRemoval()
        {
            while (activeSpill != null)
                yield return null;

            IsClean = true;
            UpdateVisual();
        }
    
        private void UpdateVisual()
        {
            spriteRendererNoCat.sprite = IsClean ? cleanSprite : dirtySprite;
        }
    }
}