using UnityEngine;

public class Player : MonoBehaviour {

    [Header("Health")]
    public int maxHealth = 5;
    [SerializeField] private Transform playerSpawnPosition;

    [Header("Movement")]
    [SerializeField] private float moveSpeed = 5f;

    [Header("Player Jump")]
    [SerializeField] private float extraJumps = 2f;
    [SerializeField] private Transform groundCheckPoint;
    [SerializeField] private float checkRadius = .2f;
    [SerializeField] private LayerMask whatIsGround;
    [SerializeField] private float jumpHeight = 12f;

    private float totallJumps;
    private bool isGround;
    private float movement;
    private bool facingRight;
    private bool victory;

    private Rigidbody2D rb;
    private Animator animator;

    [Header("Attack")]
    [SerializeField] private Transform attackPoint;
    [SerializeField] private float attackRadius = 1f;
    [SerializeField] private LayerMask whatIsEnemy;

    [Header("UI")]
    [SerializeField] private GameObject bg;
    [SerializeField] private GameObject victoryBG;
    private bool isPlayerDied;

    void Start() {

        victory = false;
        facingRight = true;
        isPlayerDied = false;
        totallJumps = extraJumps;

        rb = this.GetComponent<Rigidbody2D>();
        animator = this.GetComponent<Animator>();
        bg.transform.localPosition = new Vector3(0f, -1500f, 0f);
        victoryBG.transform.localPosition = new Vector3(0f, -1200f, 0f);
    }

    void Update() {

        if (victory) {
            movement = 0f;
            animator.SetFloat("Run", 0f);
            return;
        }

        movement = Input.GetAxis("Horizontal");
        movement = SimpleInput.GetAxis("Horizontal");

        Flip();

        isGround = Physics2D.OverlapCircle(groundCheckPoint.position, checkRadius, whatIsGround);

        if (isGround) {
            totallJumps = extraJumps;
        }

        if (Input.GetKeyDown(KeyCode.Space)) {
            Jump();
        }

        if (Mathf.Abs(movement) > 0f) {
            animator.SetFloat("Run", 1f);
        }
        else if (movement <= 0f) {
            animator.SetFloat("Run", 0f);
        }

        if (Input.GetMouseButtonDown(0)) {
            //PlayAttackAnimation();
        }
    }

    private void FixedUpdate() {
        transform.position += new Vector3(movement, 0f, 0f) * Time.fixedDeltaTime * moveSpeed;
    }

    public void TriggerVictoryUI() {
        victoryBG.LeanMoveLocalY(0f, .8f).setEaseOutBack();
    }

    public void Attack() {
        Collider2D collInfo = Physics2D.OverlapCircle(attackPoint.position, attackRadius, whatIsEnemy);

        if (collInfo) {
            
            if (collInfo.gameObject.GetComponent<Enemy1>() != null) {
                collInfo.gameObject.GetComponent<Enemy1>().TakeDamage(1);
            }
            else if (collInfo.gameObject.GetComponent<Enemy2>() != null) {
                collInfo.gameObject.GetComponent<Enemy2>().TakeDamage(1);
            }

            if (collInfo.gameObject.GetComponent<Destructible>() != null) {
                collInfo.gameObject.GetComponent<Destructible>().TriggerAnimation();
            }
        }
    }

    public void PlayAttackAnimation() {
        int attackIndex = Random.Range(0, 3);

        if (attackIndex == 0) {
            animator.SetTrigger("Attack1");
        }
        else if (attackIndex == 1) {
            animator.SetTrigger("Attack2");
        }
        else {
            animator.SetTrigger("Attack3");
        }
    }

    void Flip() { 
        
        if (movement < 0f && facingRight) {
            transform.eulerAngles = new Vector3(0f, -180f, 0f);
            facingRight = false;
        }
        else if (movement > 0f && !facingRight) {
            transform.eulerAngles = new Vector3(0f, 0f, 0f);
            facingRight = true;
        }
    }

    public void TakeDamage(int damageAmount) {
        if (maxHealth <= 1) {
            Die();
            maxHealth = 0;
            return;
        }
        else {
            maxHealth -= damageAmount;
            CameraShake.instance.Shake(.1f, 3f);
            transform.position = playerSpawnPosition.position;
        }
    }

    public void Jump() {

        if (totallJumps > 0f) {
            Vector2 velocity = rb.linearVelocity;
            velocity.y = jumpHeight;
            rb.linearVelocity = velocity;
            animator.SetBool("Jump", true);
            totallJumps--;
        } 
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground") {
            animator.SetBool("Jump", false);
        }

        if (collision.gameObject.tag == "Trap") {
            TakeDamage(1);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Trap") {
            TakeDamage(1);
        }

        if (collision.gameObject.tag == "Flag") {
            Debug.Log("Victory");
            TriggerVictoryUI();
            victory = true;
        }
    }

    private void OnDrawGizmosSelected() {

        if (groundCheckPoint != null) {
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(groundCheckPoint.position, checkRadius);
        }

        if (attackPoint != null) {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(attackPoint.position, attackRadius);
        }
    }

    void Die() {
        Debug.Log(this.gameObject.name + " Died!");
        bg.LeanMoveLocalY(0f, .8f).setEaseOutBack();
        Destroy(this.gameObject);
    }
}
