using UnityEngine;
using TMPro;

public class PlayerMovement : MonoBehaviour
{
    public static PlayerMovement Instance;

    public Transform playerTransform;
    public Transform playerTransformRotation;
    private Rigidbody playerBody;
    public bool canMove;
    // Rotation
    public float rotationSpeed;
    // Arrow 
    public Transform arrowTransform;
    public Transform spaceshipTranform;
    public static Transform arrowTarget;
    // Spaceship parts
    public Transform grabObjectTranform;
    public float playerMovementSpeed;
    private Vector3 movementDirection;
    private float energyTimer = 0;
    // Jetpack
    public ParticleSystem jetpackFire;

    public Transform spaceshipPartObject;

    [Header("Component References")]
    public PlayerStatsManager statsManager;

    [Header("Visor UI References")]
    public TMP_Text xCoordLabel;
    public TMP_Text zCoordLabel;

    [Header("Line renderer")]
    public LineRenderer lineRenderer;

    private void Start()
    {
        playerBody = GetComponent<Rigidbody>();
        Instance = this;
        arrowTarget = spaceshipTranform;
    }

    public void Update()
    {
        arrowTransform.LookAt(arrowTarget);

        if (!canMove)
            return;

        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
        {
            if (jetpackFire.isStopped)
                jetpackFire.Play();

            movementDirection = playerTransform.forward * Input.GetAxisRaw("Vertical");

            playerBody.velocity = movementDirection * playerMovementSpeed;

            xCoordLabel.text = playerTransform.position.x.ToString("#.#####");
            zCoordLabel.text = playerTransform.position.z.ToString("#.#####");

            energyTimer += Time.deltaTime;
            if (energyTimer >= 1)
            {
                statsManager.ModifyEnergy(-1);
                energyTimer = 0;
            }

            transform.Rotate(Input.GetAxisRaw("Horizontal") * Vector3.up * rotationSpeed * Time.deltaTime);
        }
        else
        {
            playerBody.velocity = Vector3.zero;
            jetpackFire.Stop();
        }


       

        if(spaceshipPartObject != null)
        {
            spaceshipPartObject.position = Vector3.Lerp(spaceshipPartObject.position, grabObjectTranform.position, 1f * Time.deltaTime);
            
            if (!lineRenderer.enabled)
                lineRenderer.enabled = true;
            
            lineRenderer.SetPosition(0, transform.localPosition);
            lineRenderer.SetPosition(1, spaceshipPartObject.localPosition);
        }
        else
        {
            if (lineRenderer.enabled)
                lineRenderer.enabled = false;
        }
    }

    public void SwithMoveBehaviour(bool p_state)
    {
        canMove = p_state;
    }


    public void CancelMovement()
    {
        playerBody.velocity = Vector3.zero;
    }


}
