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

public class FishAttack : MonoBehaviour
{
    [Header("Fish Settings")]
    public GameObject fishPrefab; // Prefab of the fish
    public GameObject platformPrefab; // Prefab of the platform
    [SerializeField] GameObject alertPrefab;
    private float jumpSpeed = 20f; // Speed of the fish's jump
    private float jumpHeight = 3f; // Height of the fish's jump
    private float maxScaleFactor = 1.8f; // Maximum size the fish grows during the jump
    private float platformDistanceMin = 25f; // Minimum distance to spawn the platform
    private float platformDistanceMax = 50f; // Maximum distance to spawn the platform
    public string bubbleLayerName = "Bubble"; // Name of the bubble layer

    private GameObject fishInstance; // Reference to the spawned fish
    private GameObject platformInstance; // Reference to the spawned platform

    IEnumerator Start()
    {
        // Ignore collisions between the fish and the bubble layer
        int bubbleLayer = LayerMask.NameToLayer(bubbleLayerName);
        int fishLayer = gameObject.layer;

        if (bubbleLayer != -1 && fishLayer != -1)
        {
            Physics2D.IgnoreLayerCollision(fishLayer, bubbleLayer);
        }
        else
        {
            Debug.LogError("Fish or Bubble layer not set up correctly in Unity!");
        }
        GameObject alert = Instantiate(alertPrefab, transform.position, Quaternion.identity);
        yield return new WaitForSeconds(1f);
        // Spawn a fish and make it jump to a random platform
        SpawnFishAndPlatform();
        Destroy(alert);
    }

    void SpawnFishAndPlatform()
    {
        if (fishPrefab == null || platformPrefab == null)
        {
            Debug.LogError("Fish or Platform prefab is not assigned!");
            return;
        }

        // Spawn the fish at the position of the shooter
        fishInstance = Instantiate(fishPrefab, transform.position, Quaternion.identity);

        // Create a random position for the platform in a random direction
        Vector2 randomDirection = Random.insideUnitCircle.normalized;
        Vector2 platformPosition = (Vector2)transform.position + randomDirection * Random.Range(platformDistanceMin, platformDistanceMax);
        platformPosition  = CheckPlatformCoords(platformPosition);
        // Spawn the platform at the calculated position
        platformInstance = Instantiate(platformPrefab, platformPosition, Quaternion.identity);

        // Make the fish jump to the platform
        FishJump(platformPosition);
    }

    Vector2 CheckPlatformCoords(Vector2 platformPosition)
    {
        if (Physics2D.OverlapCircle(platformPosition, 3f) != null)
        {
            Debug.Log("recoorded");
            Vector2 randomDirection = Random.insideUnitCircle.normalized;
            platformPosition = (Vector2)transform.position + randomDirection * Random.Range(platformDistanceMin, platformDistanceMax);
            return CheckPlatformCoords(platformPosition);
        }
        return platformPosition;
    }

    void FishJump(Vector2 targetPosition)
    {
        if (fishInstance == null)
        {
            Debug.LogError("Fish instance is null!");
            return;
        }

        StartCoroutine(HandleFishJump(targetPosition));
    }

    IEnumerator HandleFishJump(Vector2 targetPosition)
    {
        // Depending on the number of fish being spawned, the audio might be too much. Needs testing
        fishInstance.GetComponent<EnemyAudioHandler>().PlayAudio();
        Vector2 startPosition = fishInstance.transform.position;
        float totalDistance = Vector2.Distance(startPosition, targetPosition);
        float progress = 0f;

        Vector3 originalScale = fishInstance.transform.localScale;

        // Calculate the angle to face the target position
        Vector2 direction = targetPosition - startPosition;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        fishInstance.transform.rotation = Quaternion.Euler(0, 0, angle);

        while (progress < 1f)
        {
            // Update progress
            progress += jumpSpeed * Time.deltaTime / totalDistance;

            // Interpolate position
            Vector2 currentPosition = Vector2.Lerp(startPosition, targetPosition, progress);
            currentPosition.y += Mathf.Sin(progress * Mathf.PI) * jumpHeight; // Arc for the jump
            fishInstance.transform.position = currentPosition;

            // Interpolate scale
            float scaleProgress = progress <= 0.5f ? progress * 2 : (1 - progress) * 2;
            float currentScale = Mathf.Lerp(1f, maxScaleFactor, scaleProgress);
            fishInstance.transform.localScale = originalScale * currentScale;

            yield return null;
        }

        // Reset fish scale to original after the jump
        fishInstance.transform.localScale = originalScale;

        // Destroy the platform, fish, and shooter after the jump
        if (platformInstance != null)
        {
            Destroy(platformInstance);
        }

        Destroy(fishInstance);
        Destroy(gameObject);
    }
}