using UnityEngine;
using UnityEngine.Rendering.Universal;
using static UnityEngine.GraphicsBuffer;

public class ThrowableHand : Tool
{
    [Header("Throwable Hand Parameters")]
    public float range;
    public float forceModifier;
    public float loft;
    public GameObject testBomb;
  
    // Mathematical plane used to catch the raycast from camera to get direction for
    // looking at the mouse
    private Plane handGroundPlane;
    private DecalProjector targetProjection;
    private float throwForce;

    private void Update()
    {
        if (GameManager.Instance.PlayerController != null)
        {
            SetGroundPlane();
            DrawTargetProjection();
        }
    }

    private void SetGroundPlane()
    {
        if (handGroundPlane == null)
        {
            handGroundPlane = new Plane(Vector3.up, -GameManager.Instance.PlayerController.DougBody.transform.position.y);
        }

        handGroundPlane.distance = -GameManager.Instance.PlayerController.DougBody.transform.position.y;
        handGroundPlane.normal = Vector3.up;
    }

    private void DrawTargetProjection()
    {
        if (targetProjection == null)
        {
            targetProjection = GetComponentInChildren<DecalProjector>();
        }

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (handGroundPlane.Raycast(ray, out var distance))
        {
            Vector3 hitPoint = ray.GetPoint(distance);

            float distanceFromPoint = Vector3.Distance(hitPoint, transform.position);
            if (distanceFromPoint > range)
            {
                Vector3 directionTowardMouse = (hitPoint - transform.position).normalized;
                targetProjection.transform.position = new Vector3(transform.position.x, hitPoint.y, transform.position.z);
                targetProjection.transform.position += directionTowardMouse * range;

                throwForce = range;
            }
            else
            {
                targetProjection.gameObject.SetActive(true);
                targetProjection.transform.position = hitPoint;
                throwForce = distanceFromPoint;
            }
        }
    }

    public override void Use()
    {
        GameObject newBomb = Instantiate(testBomb);
        newBomb.transform.position = transform.position;

        Vector3 direction = transform.forward * throwForce * forceModifier;
        direction += GameManager.Instance.PlayerController.GetVelocity();
        direction.y = loft;

        newBomb.GetComponent<Rigidbody>().AddForce(direction, ForceMode.Impulse);
    }

    public override void UseAlt()
    {
        throw new System.NotImplementedException();
    }
}
