using Unity.VisualScripting;
using UnityEngine;

public class Move : MonoBehaviour
{
    static public Move Instance;
    [Range(0, 1)]
    [SerializeField] float playerAccelerationSpeed;
    public float playerMaxVelocity = 1;
    [Range(0, 1)]
    [SerializeField] float turnRate;
    [SerializeField] private float lastX;
    [SerializeField] private float lastZ;
    public  GameObject playerModel;
    [SerializeField] private Transform playerHolder;
    [SerializeField] private float sprintMultiplier = 1.5f;

    private float originalMaxVel;

    public bool sprintEnabled = true;
    public float minVelThreshold = 0.1f;

    private Camera mainCam;

    public Rigidbody pRB;

    private void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        mainCam = Camera.main;
        originalMaxVel = playerMaxVelocity;
    }

    void Update()
    {
        lastX = Input.GetAxisRaw("Horizontal");
        lastZ = Input.GetAxisRaw("Vertical");

        // Limit the Velocity
        Vector3 vel = pRB.velocity;
        if (Mathf.Abs(vel.x) > playerMaxVelocity)
            pRB.velocity = new Vector3(playerMaxVelocity * Mathf.Sign(vel.x), vel.y, vel.z);
        if (Mathf.Abs(vel.z) > playerMaxVelocity)
            pRB.velocity = new Vector3(vel.x, vel.y, playerMaxVelocity * Mathf.Sign(vel.z));

        Sprint();

        // Set the Rotation
        if (MoveInput)
        {
            // Use the rotation
            float Angle = Mathf.Atan2(pRB.velocity.x, pRB.velocity.z) * Mathf.Rad2Deg;
            playerModel.transform.eulerAngles = new Vector3(0, CameraScript.I.cameraHolder.transform.eulerAngles.y, 0);
            playerHolder.transform.eulerAngles = new Vector3(0, CameraScript.I.cameraHolder.transform.eulerAngles.y, 0);
            playerModel.transform.eulerAngles = new Vector3(playerModel.transform.eulerAngles.x, Angle, playerModel.transform.eulerAngles.z);
        }
    }

    private void FixedUpdate()
    {
        pRB.velocity = Vector3.Slerp(pRB.velocity, (playerHolder.transform.right * lastX * playerMaxVelocity) + (playerHolder.transform.forward * lastZ * playerMaxVelocity), playerAccelerationSpeed);
    }

    private void Sprint()
    {
        print("Received");
        if (sprintEnabled)
        {
            if (Input.GetKeyDown(KeyCode.LeftShift))
                playerMaxVelocity = originalMaxVel * sprintMultiplier;
            else
                playerMaxVelocity = originalMaxVel;
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.green;

        if (pRB != null)
        {
            Gizmos.color = Color.yellow;
            Gizmos.DrawSphere(transform.position + pRB.velocity.normalized, 0.1f);
        }
    }

    public bool Moving => Mathf.Abs(pRB.velocity.x) > minVelThreshold || Mathf.Abs(pRB.velocity.z) > minVelThreshold;

    private bool MoveInput => (lastX != 0 || lastZ != 0);
    private bool IsMovementY() => pRB.velocity.y > minVelThreshold;
}