using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(PlayerInput))]
public class PlayerMovement : MonoBehaviour {
	public PlayerData data;
	
	new Rigidbody rigidbody;
	Vector2 moveInput;
	Vector3 moveDirection;
	Transform camTransform;

	public TextMeshProUGUI freeAngleText;
	public TextMeshProUGUI roundedAngleText;

	void Awake() {
		rigidbody = GetComponent<Rigidbody>();

		var playerInput = GetComponent<PlayerInput>();

		playerInput.actions["Move"].started += OnMove;
		playerInput.actions["Move"].performed += OnMove;
		playerInput.actions["Move"].canceled += OnMove;

		if (Camera.main != null)
			camTransform = Camera.main.transform;
		else
			Debug.LogError("Couldn't find the main camera.");
	}

	void Update() {
		Vector3 camForward = camTransform.forward;
		camForward.y = 0;
		camForward.Normalize();
		
		//free moveDirection
		moveDirection = camForward * moveInput.y + camTransform.right * moveInput.x;
		
		float angle = Vector3.SignedAngle(Vector3.forward, moveDirection, Vector3.up);
		freeAngleText.text = "FreeAngle: " + Mathf.RoundToInt(angle);

		float deltaAngle = Mathf.Sign(angle) * 29;
		deltaAngle -= (deltaAngle + angle) % 60;
		roundedAngleText.text = "RoundedAngle: " + Mathf.RoundToInt(angle + deltaAngle);

		var rotation = Quaternion.AngleAxis(deltaAngle, Vector3.up);
		moveDirection = rotation * moveDirection;
	}

	void FixedUpdate() {
		if (moveDirection != Vector3.zero) {
			rigidbody.MovePosition(rigidbody.position + moveDirection * data.speed * Time.fixedDeltaTime);

			AlignGroundedRotation();
		}
	}

	void AlignGroundedRotation() {
		Quaternion goalRot = Quaternion.LookRotation(moveDirection);
		Quaternion slerp = Quaternion.Slerp(transform.rotation, goalRot, data.turnSpeed * moveDirection.magnitude * Time.fixedDeltaTime);

		transform.rotation = slerp;
	}

	void OnMove(InputAction.CallbackContext ctx) {
		Vector2 input = ctx.ReadValue<Vector2>();
		if (input.sqrMagnitude > 1f)
			input.Normalize();

		moveInput = input;
	}
}