using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class BloodSucker : MonoBehaviour {

    [SerializeField] float suckDuration = 1f;
    [SerializeField] float suckRange = 1f;
    [SerializeField] float healthGainFromSuck = 30f;

    Entity currentTarget;
    VampireEntity vampireEntity;
    bool isSucking;
    float currentSuckTimer;

    void Awake() {
        vampireEntity = GetComponent<VampireEntity>();
    }

    void FixedUpdate() {
        if (currentTarget == null) {
            SearchSuckTarget();
        }

        if (currentTarget != null) {
            if (Vector3.Distance(currentTarget.transform.position, transform.position) > suckRange) {
                SetTarget(null);
            } else {
                if (isSucking) {
                    PerformSuck(Time.fixedDeltaTime);
                    // } else {
                    //     HighlightTarget();
                }
            }
        }
    }

    public void ToggleSuck(InputAction.CallbackContext context) {
        if (context.performed) {
            if (currentTarget != null) {
                isSucking = true;
                currentSuckTimer = suckDuration;
            }
        } else if (context.canceled) {
            isSucking = false;
        }
    }

    void SearchSuckTarget() {
        foreach (Collider2D coll in Physics2D.OverlapCircleAll(transform.position, suckRange)) {
            Entity entity = coll.GetComponent<Entity>();
            if (entity != null && entity.gameObject != gameObject) {
                if (!entity.IsAlive() && entity.bloodTokens > 0) {
                    SetTarget(entity);
                }
            }
        }
    }

    void SetTarget(Entity newTarget) {
        if(newTarget != currentTarget) {
            isSucking = false;
        }
        if (currentTarget != null) {
            UnHighlightTarget();
        }

        currentTarget = newTarget;

        if (currentTarget != null) {
            // print("new target : " + currentTarget.name);
            HighlightTarget();
        }
    }

    void PerformSuck(float deltaTime) {
        currentSuckTimer -= deltaTime;
        if (currentSuckTimer < 0f) {
            currentTarget.bloodTokens -= 1;
            vampireEntity.HealDamage(healthGainFromSuck);
            // print("One token sucked");
            if (currentTarget.bloodTokens == 0) {
                SetTarget(null);
                isSucking = false;
                // TODO : Dispawn target
            } else {
                currentSuckTimer = suckDuration;
            }
        }
    }

    void HighlightTarget() {
        currentTarget.EnableHalo();
    }

    void UnHighlightTarget() {
        currentTarget.DisableHalo();
    }

}
