using System;
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class MovementWASD : MonoBehaviour
{
    [SerializeField] private Animator _animator;
    [SerializeField] private Transform _playerModel;
    public InputManager inputManager;
    
    public int moveSpeed = 5;
    private CharacterController charCon;
    public float pickUpTime=3f;
    
    [SerializeField]
    private InteractionWheel _interactionWheel;

    [SerializeField] private Transform model;
    [SerializeField] private InventoryManager inventoryManager;
    [SerializeField] private AudioSource collect;
    
    public int health { get; set; }

    void Start()
    {
        health = 3;
        this.charCon = GetComponent<CharacterController>();
        charCon.detectCollisions = true;
    }

    void Update()
    {
        model.localPosition = Vector3.zero;
        model.localRotation = Quaternion.Euler(0f, 0f, 0f);
        if (!InteractingWithObjects())
        {
            Move();
        }
    }

    void Move()
    {
        Vector3 moveDir = new Vector3(inputManager.moveInput.x, 0f, inputManager.moveInput.y);

        if (moveDir.magnitude > 0f)
        {
            //transform.rotation = moveDir
            _playerModel.rotation = Quaternion.LookRotation(moveDir);
        }
        
        _animator.SetFloat("Blend", moveDir.magnitude > 0f ? 1f: 0f);
        
        charCon.SimpleMove(moveDir * moveSpeed);
    }

    private GameObject present = null;
    private void OnTriggerEnter(Collider hit)
    {
        if (hit.tag == "present")
        {
            present = hit.gameObject;
        }

        if (hit.tag == "Enemy")
        {
            inventoryManager.HealthAmount--;
        }
        
        if (hit.tag == "Juice")
        {
            collect.Play();
            StartCoroutine(hit.gameObject.GetComponent<Juice>().collected(0.5f, 40f));
        }
    }

    private void OnTriggerExit(Collider hit)
    {
        if (hit.tag == "present" && hit.gameObject == present)
        {
            present = null;
            _interactionWheel.Hide();
        }
    }

    private Coroutine _hideCoroutine = null;
    private bool interacting = false;
    bool InteractingWithObjects()
    {
        if (inputManager.interactPerformed && present != null && !interacting)
        {
            _animator.SetFloat("Blend", 3f);
            if (_hideCoroutine != null) 
            {
                StopCoroutine(_hideCoroutine);
            }
            _interactionWheel.FillWheelOverTimeToAmount(pickUpTime, 1f, present, collect);
            interacting = true;
        }else if (!inputManager.interactPerformed && interacting)
        {
            _animator.SetFloat("Blend", 0f);
            _hideCoroutine = StartCoroutine(_interactionWheel.Hide());
            interacting = false;
        }

        return interacting;
    }
}
