using System;
using UnityEngine;
using UnityEngine.InputSystem;

public class BallBehavior : MonoBehaviour
{
    private PlayerInput _playerInput;
    private InputAction _horizontalAction;
    private float _horizontalAxis;
    public int moveForwardSpeed = 3;
    public float keyboardMoveSpeed = 15f;
    private int _isKeyboard;
    private GameObject _ball;
    private float _ballRadius;
    private Vector3 _ballBottomPos;
    private Boolean _gameOver = false;
    
    private Boolean _hasTriggeredPlatform = false;
    
    // Ground Checks
    [Header("Ground Checks")]
    [SerializeField] private bool isGrounded;
    [SerializeField] private float groundCheckDistance = 0.17f;
    [SerializeField] private LayerMask groundMask = 0;

    void Awake()
    {
        _playerInput = GetComponent<PlayerInput>();
        _horizontalAction = _playerInput.currentActionMap.FindAction("Horizontal");
        _horizontalAction.performed += MoveActionPerformed;
        _horizontalAction.canceled += _ => _horizontalAxis = 0;
    }

    void Start()
    {
        _ball = GameObject.Find("Ball");
        _ballRadius = _ball.GetComponent<SphereCollider>().radius;
    }

    void Update()
    {
        if(!_gameOver)
        {
            Vector3 position = transform.position;
            var deltaTime = Time.deltaTime;
            position += Vector3.forward * (moveForwardSpeed * deltaTime);
            position += Vector3.right * (deltaTime * _horizontalAxis);
            transform.position = position;
        }
        
        _ballBottomPos = _ball.transform.position + Vector3.down * _ballRadius;
        
        // isGrounded -> Weird condition because of the trigger check
        if (!Physics.CheckSphere(_ballBottomPos, groundCheckDistance, groundMask))
        {
            if (isGrounded)
            {
                _hasTriggeredPlatform = false;
            }
            isGrounded = false;
        }
        else
        {
            isGrounded = true;
        }
        
        if(_ball.transform.position.y < 0.6f && !isGrounded)
        {
            Debug.Log("Game Over: " + _ball.transform.position.y + " " + isGrounded);
            _gameOver = true;
        }
    }

    private void FixedUpdate()
    {
        if (!_hasTriggeredPlatform && isGrounded)
        {
            // We have to get the gameobject just below with a raycast
            Collider[] hitColliders = Physics.OverlapSphere(_ballBottomPos, groundCheckDistance, groundMask);
            foreach (var hitCollider in hitColliders)
            {
                if (hitCollider.gameObject.CompareTag("Platform"))
                {
                    hitCollider.gameObject.GetComponent<PlatformsBehavior>().setActive();
                    Debug.Log("Platform Triggered");
                    _hasTriggeredPlatform = true;
                }
            }
        }
    }

    private void MoveActionPerformed(InputAction.CallbackContext context)
    {
        if (context.control.device.displayName.Contains("Keyboard"))
        {
            _isKeyboard = 1;
        }
        else
        {
            _isKeyboard = 0;
        }

        _horizontalAxis = context.ReadValue<float>() * (1 + keyboardMoveSpeed * _isKeyboard);
    }
    
    void OnDrawGizmosSelected()
    {
        // Dessine une boule rouge pour visualier goundCheckDistance
        Gizmos.color = Color.red;
        Gizmos.DrawSphere(_ballBottomPos, groundCheckDistance);
    }

    public void RestartScene()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene(0);
    }
}