using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace UNSLOW.EffectPractice.FirstTerm.Gauges
{
    [ExecuteInEditMode]
    public class RingGauge : MonoBehaviour
    {
        private static readonly int PropertyColorA = Shader.PropertyToID("_Color_A");
        private static readonly int PropertyColorB = Shader.PropertyToID("_Color_B");
        private static readonly int PropertyPhase = Shader.PropertyToID("_Phase");

        [SerializeField]
        private Image image;

        [SerializeField]
        private float range = 0.75f;
        
        [SerializeField]
        [Range(0, 1)]
        private float value = 1f;

        [SerializeField]
        private TMP_Text text;
        
        [SerializeField] private Gradient gradientA, gradientB;

        private float _phase;
        
        public float Value
        {
            get => value;
            set
            {
                this.value = value;
                image.fillAmount = value *  range;
                
                text.text = $"LIFE\n{(int)(value*100)}%";
                
                image.material.SetColor(PropertyColorA, gradientA.Evaluate(value));
                image.material.SetColor(PropertyColorB, gradientB.Evaluate(value));
            }
        }

        private void LateUpdate()
        {
            _phase += Time.deltaTime * Mathf.Lerp(4f, 1f, value);
            _phase %= Mathf.PI * 2f;
            image.material.SetFloat(PropertyPhase, _phase);
        }
        
        private void OnValidate()
        {
            Value = value;
        }
    }
}
