using System;
using UnityEngine;
using UnityEngine.AI;

public class PlayerMover : MonoBehaviour
{
    public Transform _destination;
    NavMeshAgent _agent;

    void Awake()
    {
        _agent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        Move();
    }

    void Move()
    {
        if (_destination != null && _agent != null)
        {
            _agent.enabled = true;
            if (_agent.pathStatus == NavMeshPathStatus.PathInvalid)
            {
                transform.position = _destination.position;
                _agent.enabled = false;
                _agent.enabled = true;
                Debug.Log($"Teleported {gameObject.name} to {_destination.position}", gameObject);
            }
            else if (_agent.remainingDistance <= 0.25f)
                transform.forward = _destination.forward;

            float distanceMod = _agent.remainingDistance / 30f;
            _agent.speed = Mathf.Lerp(1.5f, 8f, distanceMod);

            _agent.SetDestination(_destination.position);
        }
    }

    public void SetDestination(Transform destination)
    {
        if (_destination == destination)
            return;
        
        _destination = destination;
        var path = new NavMeshPath();
        NavMesh.CalculatePath(transform.position, _destination.position, NavMesh.AllAreas, path);

        if (path.status == NavMeshPathStatus.PathInvalid)
        {
            if (NavMesh.SamplePosition(transform.position, out var hit, float.MaxValue, NavMesh.AllAreas))
            {
                transform.position = hit.position;
                Debug.Log($"Teleported {gameObject.name} to {hit.position}", gameObject);
            }
        }
    }

    public void Stop()
    {
        if (_agent.isOnNavMesh)
            _agent.isStopped = true;
        _agent.enabled = false;
        enabled = false;
    }


    void OnDrawGizmosSelected()
    {
        Gizmos.color = _agent.isOnNavMesh ? Color.green : Color.red;
        if (_destination != null)
            Gizmos.DrawLine(transform.position, _destination.position);
    }
}