using Darkmatter.Core;
using System.Collections;
using Unity.Cinemachine;
using UnityEngine;
using VContainer;

namespace Darkmatter.Presentation
{
    public class Player : MonoBehaviour, IPlayer
    {
        [SerializeField] private float jumpForce = 3f;
        [SerializeField] private Rigidbody rb;
        [SerializeField] private GameObject splashObject;
        [SerializeField] private ParticleSystem deadParticle;
        [SerializeField] private ParticleSystem jumpParticle;
        [SerializeField] private CinemachineImpulseSource cinemachineImpulseSource;

        [SerializeField] private Material playerMaterial;
        [SerializeField] Color[] playerMaterialColors;

        public bool isDead { get; private set; }

        [Inject] private IDeathScreenController IdeathScreenController;
        [Inject] private IInputReader IinputReader;
        [Inject] private IAudioController IaudioController;
        [Inject] private IPool<Splash> ISplashPool;


        private void Start()
        {
            isDead = false;
            playerMaterial.color = playerMaterialColors[Random.Range(0, playerMaterialColors.Length)];
            
        }

        private void OnCollisionEnter(Collision collision)
        {
            ShowAndHideSplash(collision);
            if (isDead) return;

            if (collision.gameObject.CompareTag("Safe") && rb.linearVelocity.y <= 0.5f)
            {
                rb.linearVelocity = Vector3.up * jumpForce;
                jumpParticle.Play();
                IaudioController.PlayJumpSound();
            }
            else if (collision.gameObject.CompareTag("Death"))
            {
                Die();
            }
        }

        private void ShowAndHideSplash(Collision collision)
        {
            float splashYPos = collision.transform.position.y + 0.155f;
            ContactPoint contact = collision.contacts[0];
            Vector3 surfacePoint = new Vector3(contact.point.x, splashYPos, contact.point.z);

            Splash currentSplash = ISplashPool.GetFromPool();
            currentSplash.transform.position = surfacePoint;
            currentSplash.transform.SetParent(collision.gameObject.transform);
            currentSplash.transform.localScale = new Vector3(Random.Range(0.05f, 0.09f), Random.Range(0.05f, 0.09f), 1);
            currentSplash.ReturnToPool();
        }
        private void Die()
        {
            isDead = true;
            IinputReader.LockInput();
            deadParticle.Play();
            this.GetComponent<Renderer>().enabled = false;
            IaudioController.PlayDeathSound();
            Handheld.Vibrate(); //Vibration
            cinemachineImpulseSource.GenerateImpulseWithForce(1);
            StartCoroutine(DieRoutine());
        }

        IEnumerator DieRoutine()
        {
            yield return new WaitForSeconds(1f);
            IdeathScreenController.ShowDeathScreen();
        }
    }

}
