using System;
using System.Collections;
using Intrepid.Utilities;
using UnityEngine;
using UnityEngine.UI;

namespace Intrepid.Gameplay.Codex.UI.Components
{
    public class CodexColorLerpEffectUI : CodexColorEffectUI
    {
        [SerializeField] private bool useUnscaledTime = true;
        [SerializeField, Min(0.05f)] private float duration = 0.12f;
        [SerializeField] private AnimationCurve curve = AnimationCurve.EaseInOut(0, 0, 1, 1);

        private Coroutine Routine { get; set; }
        
        public override void Apply(Graphic target, Color targetColor)
        {
            if (target.IsNull()) return;

            if (Routine is not null)
            {
                StopCoroutine(Routine);
                Routine = null;
            }
            
            Routine = StartCoroutine(TransitionRoutine(target, targetColor));
        }

        private IEnumerator TransitionRoutine(Graphic target, Color targetColor)
        {
            var sourceColor = target.color;
            var elapsed = 0f;

            while (elapsed < duration)
            {
                elapsed += useUnscaledTime ? Timer.UnscaledTime : Timer.ScaledTime;

                var t = Mathf.Clamp01(elapsed / duration);
                var eased = curve?.Evaluate(t) ?? t;

                target.color = Color.LerpUnclamped(sourceColor, targetColor, eased);
                yield return null;
            }

            target.color = targetColor;
            Routine = null;
        }
        
        public override void Stop(Graphic target)
        {
            if (Routine is not null)
            {
                StopCoroutine(Routine);
                Routine = null;
            }
        }
    }
}