using System.Collections;
using Assets._game.scripts;
using UnityEngine;
using UnityEngine.UI;

public class UIPlayerSelectItem : MonoBehaviour
{
    public Text NameLabel;
    public Image Image;
    public Button SelectButton;
    public Image BackgroundImage;
    public Image Indicator;
    public Text FireRateLabel;
    public Text HitpointsLabel;
    public Text ProjectileLabel;
    public Text SpeedLabel;
    public CanvasGroup Group;//THe entire widget
    public float FadeInTime = 0.5f;
    public int CurrentPlayerId;
    public bool isConfirmed;

    public delegate void SelectionChangeHAndler(Player player);

    public event SelectionChangeHAndler SelectionChanged;

    private PlayerData _data;
    
    private Player _player;

    public void Start()
    {
        Indicator.enabled = false;
        CurrentPlayerId = -1;
        Group.alpha = 0;
    }

    public void Setup(PlayerData data, float delay = 0)
    {
        _data = data;
        Refresh();
        StartCoroutine(FadeIn(delay));
    }

    public void Select(int playerId)
    {
        CurrentPlayerId = playerId;
        Indicator.enabled = true;
        Indicator.color = GameManager.GetPlayerColor(playerId, 0.5f);
    }

    public void Deselect()
    {
        CurrentPlayerId = -1;
        Indicator.enabled = false;
    }

    public void Confirm()
    {
        if (isConfirmed)
        {
            return;
        }
        
        _player = GameManager.Instance.AddPlayer(_data, CurrentPlayerId);
        isConfirmed = true;
        Indicator.color = GameManager.GetPlayerColor(CurrentPlayerId, 0.8f);
        
        if (SelectionChanged != null)
        {
            SelectionChanged(_player);
        }
    }

    private void Refresh()
    {
        CurrentPlayerId = -1;
        NameLabel.text = _data.Name;
        Image.sprite = _data.Sprite;
        FireRateLabel.text = string.Format("Fire rate: {0:0.0}", _data.FireRate);
        HitpointsLabel.text = string.Format("Hitpoints: {0:0}", _data.HitPoints);
        SpeedLabel.text = string.Format("Speed: {0:0}", _data.MoveSpeed);
        ProjectileLabel.text = string.Format("{0}s - Damage: {1}", _data.Projectile.name, _data.Projectile.HitDamage);
    }

    private IEnumerator FadeIn(float delay)
    {
        if (delay > 0f)
        {
            yield return new WaitForSeconds(delay);
        }

        float startTime = Time.timeSinceLevelLoad;
        float endTime = startTime + FadeInTime;
        
        while (Time.timeSinceLevelLoad < endTime)
        {
            Group.alpha = Mathf.InverseLerp(startTime, endTime, Time.timeSinceLevelLoad);
            yield return null;
        }
    }
}
