using System.Collections;
using UnityEngine;

public class BossEnemyShooter : MonoBehaviour
{
    public float moveSpeed = 2f;
    public float jumpForce = 5f; // The force of the boss's jump
    public float jumpInterval = 3f; // Interval between jumps
    public float shootInterval = 2f;
    public GameObject bulletPrefab;
    public Transform gunTransform;
    public Transform firePoint;
    public float bulletSpeed = 10f;
    public float detectionRange = 10f;
    public Vector2[] movePattern; // Array of points to define the boss's movement pattern

    private Transform player;
    private Rigidbody2D rb;
    private bool facingRight = true;
    private int currentMoveIndex = 0; // Index to track the current point in the move pattern
    private bool movingForward = true; // Track movement direction in the pattern

    private void Awake()
    {
        player = FindObjectOfType<PlayerMovement>().transform;
        rb = GetComponent<Rigidbody2D>();
    }

    private void Start()
    {
        // Start the boss's jumping and shooting routines
        StartCoroutine(JumpAtIntervals());
        StartCoroutine(ShootAtIntervals());
    }

    private void Update()
    {
        // Aim at the player if in range
        if (PlayerInRange())
        {
            AimAtPlayer();
        }
    }

    private void FixedUpdate()
    {
        // Move to the next point in the pattern in FixedUpdate for consistent physics calculations
        MoveInPattern();
    }

    private bool PlayerInRange()
    {
        return Vector2.Distance(transform.position, player.position) <= detectionRange;
    }

    private void MoveInPattern()
    {
        if (movePattern.Length == 0) return; // Return if no pattern is defined

        // Move towards the current point in the pattern
        Vector2 targetPosition = movePattern[currentMoveIndex];
        Vector2 direction = (targetPosition - (Vector2)transform.position).normalized;
        rb.velocity = new Vector2(direction.x * moveSpeed, rb.velocity.y);

        // Check if the boss is close to the target position
        if (Vector2.Distance(transform.position, targetPosition) < 0.1f)
        {
            // Update the move index based on the movement direction
            if (movingForward)
            {
                currentMoveIndex++;
                if (currentMoveIndex >= movePattern.Length)
                {
                    currentMoveIndex = movePattern.Length - 1;
                    movingForward = false;
                }
            }
            else
            {
                currentMoveIndex--;
                if (currentMoveIndex < 0)
                {
                    currentMoveIndex = 0;
                    movingForward = true;
                }
            }
        }

        // Flip the boss to face the direction it's moving
        if ((direction.x > 0 && !facingRight) || (direction.x < 0 && facingRight))
        {
            Flip(direction.x);
        }
    }

    private IEnumerator JumpAtIntervals()
    {
        while (true)
        {
            yield return new WaitForSeconds(jumpInterval);
            Jump();
        }
    }

    private void Jump()
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }

    private void AimAtPlayer()
    {
        Vector2 direction = player.position - gunTransform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        // Adjust the angle based on the facing direction
        gunTransform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

        // Flip the boss to face the shooting direction
        if ((direction.x > 0 && !facingRight) || (direction.x < 0 && facingRight))
        {
            Flip(direction.x);
        }
    }

    private void Flip(float direction)
    {
        facingRight = direction > 0;
        Vector3 theScale = transform.localScale;
        theScale.x = facingRight ? Mathf.Abs(theScale.x) : -Mathf.Abs(theScale.x);
        gunTransform.GetComponent<SpriteRenderer>().flipY = !facingRight;
        gunTransform.localScale *= -1f;
        transform.localScale = theScale;
    }

    private IEnumerator ShootAtIntervals()
    {
        while (true)
        {
            yield return new WaitForSeconds(shootInterval);
            if (PlayerInRange())
            {
                Shoot();
            }
        }
    }

    private void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D bulletRb = bullet.GetComponent<Rigidbody2D>();
        bulletRb.velocity = firePoint.right * bulletSpeed;
    }

    private void OnDestroy()
    {
        GameManager.instance.GameWin();
    }
}
