using DG.Tweening;
using TMPro;
using UnityEngine;

public class BattlerHealthBar : MonoBehaviour
{
    [Header("Dependencies")]
    [SerializeField]
    Bar _bar;
    [SerializeField]
    Battler _battler;

    [SerializeField]
    TMP_Text Label;
    
    void Awake()
    {
        _battler.HealthChanged += ApplyHealthChange;
        _battler.PlayerChanged += OnPlayerChanged;
        _battler.Won += OnWon;
        _battler.Died += OnDied;
        _battler.TookHit += OnTookHit;
    }

    void OnTookHit(int health, bool wasCrit)
    {
        _bar.Show();
    }

    void OnDied()
    {
        _bar.Hide();
    }

    bool _fightOver;
    void OnWon()
    {
        _fightOver = true;
        _bar.Replenish(()=>_bar.Hide());
        FlashTheLabel(_battler.MaxHealth,Color.green);
    }

    void OnPlayerChanged(PlayerData player)
    {
        _bar.SetColors(player.Color1, player.Color2);
        _bar.Max = _battler.MaxHealth;
        _bar.Value = _bar.Max;
        
    }

    void ApplyHealthChange(int health, int change)
    {
        _bar.Max = _battler.MaxHealth;
        _bar.Value = health;

        if (change < 0)
        {
            _bar.TakeDamage(change);
            FlashTheLabel(health, Color.red);
        }
        else
        {
            _bar.Value = health;
            string healthText = $"{health} / {_battler.MaxHealth}";
            Label.SetText(healthText);
        }
        

        if (health <= 0)
            _bar.Hide();
    }

    void FlashTheLabel(int health,Color color)
    {
        string healthText = health <= 0 ? "DEFEATED" : $"{health} / {_battler.MaxHealth}";
        DOTween.Kill(Label);
        Label.color = color;
        Label.DOColor(Color.white, 0.1f).SetEase(Ease.Flash);
        Label.DOText(healthText, 0.3f);
    }
}
