using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class Enemy : MonoBehaviour
{
    [SerializeField] private Transform pointA;
    [SerializeField] private Transform pointB;
    [SerializeField] private Transform slime;
    [SerializeField] private float speed;
    private Rigidbody2D rb;
    private Collider2D _collider;
    private Transform targetPoint;
    private bool isAttacking;

    public event EventHandler OnAttack;

    private const string PLAYER = "Player";

    private void Awake() {
        rb = slime.gameObject.GetComponent<Rigidbody2D>();
        _collider = slime.gameObject.GetComponent<Collider2D>();
    }

    private void Start() {
        targetPoint = pointA;
    }

    private void Update() {
        if (!isAttacking) {
            Patrol();
        }
        else {
            Attack();
        }
    }

    private void Patrol() {
        if (targetPoint == pointA) {
            rb.velocity = new Vector2(-speed, 0);
        }
        else {
            rb.velocity = new Vector2(speed, 0);
        }

        if (Vector2.Distance(slime.position, targetPoint.position) < 1f) {
            if(targetPoint == pointA) {
                targetPoint = pointB;
            } else if (targetPoint == pointB) {
                targetPoint = pointA;
            }

            Flip();
        }

        if (InAttackRange()) {
            Attack();
        }
    }

    private void Flip() {
        Vector2 localScale = slime.localScale;
        localScale.x *= -1;
        slime.localScale = localScale;
    }

    private bool InAttackRange() {
        float rayDistance = 5f;
        Vector2 rayDirection = rb.velocity.normalized;
        LayerMask playerLayerMask = LayerMask.GetMask(PLAYER);
        RaycastHit2D hit = Physics2D.Raycast(slime.position, rayDirection, rayDistance, playerLayerMask);

        Debug.DrawRay(slime.position, rayDirection * rayDistance, Color.red);

        if (hit.collider != null) {
            Debug.Log(hit.collider.gameObject.name);
            if (hit.collider.gameObject.layer == LayerMask.NameToLayer(PLAYER)) {
                return true;
            }
        }

        return false;
    }

    private void Attack() {
        isAttacking = true;
        OnAttack?.Invoke(this, EventArgs.Empty);
        isAttacking = false;
    }
}
