using UnityEngine;

public class Enemy2 : MonoBehaviour
{
    [Header("Health")]
    [SerializeField] private int maxHealth = 3;
    [SerializeField] private GameObject floatingTextPrefab;
    [SerializeField] private Transform spawnPoint;

    [Header("Movement")]
    [SerializeField] private float walkSpeed = 2f;
    [SerializeField] private float chaseSpeed = 4f;

    private bool facingLeft;

    [Header("Ground Detection")]
    [SerializeField] private Transform groundCheckPoint;
    [SerializeField] private float distance = .3f;
    [SerializeField] private LayerMask whatIsGround;

    [Header("Attack Checking")]
    [SerializeField] private float retrieveDistance = 2.5f;
    [SerializeField] private float attackRangeRadius = 6f;
    [SerializeField] private LayerMask whatIsPlayer;
    [SerializeField] private Transform player;

    private bool isPlayerInAttackRange;
    private Animator animator;
    private Rigidbody2D rb;
    private BoxCollider2D boxCollider2D;

    [Header("Attack")]
    [SerializeField] private Transform attackPoint;
    [SerializeField] private float attackRadius = 1f;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start() {
        facingLeft = true;
        isPlayerInAttackRange = false;
        rb = this.gameObject.GetComponent<Rigidbody2D>();
        boxCollider2D = this.gameObject.GetComponent<BoxCollider2D>();
        animator = this.gameObject.GetComponent<Animator>();
    }
    
    void Update() {

        Collider2D collInfo = Physics2D.OverlapCircle(transform.position, attackRangeRadius, whatIsPlayer);

        if (collInfo) {
            isPlayerInAttackRange = true;
        }
        else {
            isPlayerInAttackRange = false;
        }

        if (isPlayerInAttackRange == false) {
            PatrolEnemy();
            
        }
        else {

            Vector2 targetPos = new Vector2(player.position.x, transform.position.y);

            if (Vector2.Distance(transform.position, player.position) > retrieveDistance) {
                animator.SetBool("Attack", false);
                transform.position = Vector2.MoveTowards(transform.position, targetPos, chaseSpeed * Time.deltaTime);
            }
            else {
                animator.SetBool("Attack", true);
            }
            Flip();
        }
    }

    public void Attack() {

        Collider2D collInfo = Physics2D.OverlapCircle(attackPoint.position, attackRadius, whatIsPlayer);

        if (collInfo) { 
            
            if (collInfo.gameObject.GetComponent<Player>() != null) {
                collInfo.gameObject.GetComponent<Player>().TakeDamage(1);
            }
        }
    }

    void PatrolEnemy() {
        transform.Translate(Vector2.left * Time.deltaTime * walkSpeed);

        RaycastHit2D hitInfo = Physics2D.Raycast(groundCheckPoint.position, Vector2.down, distance, whatIsGround);

        if (!hitInfo) {
            if (facingLeft) {
                transform.eulerAngles = new Vector3(0f, -180f, 0f);
                facingLeft = false;
            }
            else {
                transform.eulerAngles = new Vector3(0f, 0f, 0f);
                facingLeft = true;
            }
        }
    }

    void Flip() {

        if (transform.position.x < player.position.x && facingLeft){
            transform.eulerAngles = new Vector3(0f, -180f, 0f);
            facingLeft = false;
        }
        else if (transform.position.x > player.position.x && !facingLeft) {
            transform.eulerAngles = new Vector3(0f, 0f, 0f);
            facingLeft = true;
        }
    }

    public void TakeDamage(int damageAmount) { 
        
        if (maxHealth <= 1) {
            Die();
            maxHealth = 0;
            return;
        }
        else {
            maxHealth -= damageAmount;
            animator.SetTrigger("Hurt");
            CameraShake.instance.Shake(.2f, 4f);
            GameObject tempFloatingTextPrefab = Instantiate(floatingTextPrefab, spawnPoint.position, Quaternion.identity);
            Destroy(tempFloatingTextPrefab, 1f);
        }
    }

    private void OnDrawGizmosSelected()
    {
        if (groundCheckPoint != null) {
            Gizmos.color = Color.yellow;
            Gizmos.DrawRay(groundCheckPoint.position, Vector2.down * distance);
        }

        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(transform.position, attackRangeRadius);

        if (attackPoint != null) {
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(attackPoint.position, attackRadius);
        }
    }

    void Die() {
        Debug.Log(this.gameObject.name + " Died");
        animator.SetTrigger("Death");
        rb.gravityScale = 0f;
        boxCollider2D.enabled = false;
        Destroy(this.gameObject, 5f);
    } 
}
