using System;
using UnityEngine;
using TMPro;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine.SceneManagement;

public class PlayerHealth : MonoBehaviour
{
    [SerializeField] int playerHealth;
    [SerializeField] TextMeshProUGUI healthText;
    [SerializeField] private SpriteRenderer[] partOfBodies;
    [SerializeField] private CanvasGroup diePanel;
    private List<Color> _defaultBodyColors = new List<Color>();
    private bool _canTakeDamage = true;
    private bool _playerStayInTrigger;
    private bool _lockedHealth;
    

    private void Awake()
    {
        healthText.text = "HP: " + playerHealth.ToString();
        foreach (var partOfBody in partOfBodies)
        {
            _defaultBodyColors.Add(partOfBody.color);
        }

        PlayerController.Win += LockHealth;
    }

    private void OnDestroy()
    {
        PlayerController.Win -= LockHealth;
    }

    private void Update()
    {
        if (_playerStayInTrigger)
        {
            DecreasePlayerHealth(1);
        }
    }

    void LockHealth()
    {
        _lockedHealth = true;
    }
    public void DecreasePlayerHealth(int value)
    {
        if(_lockedHealth) return;

        if(_canTakeDamage)
        {
            _canTakeDamage = false;
            playerHealth -= value;
            healthText.text = "HP: " + playerHealth.ToString();
            if(playerHealth <= 0)
            {
                Die();
            }
            else
            {
                StartCoroutine(ChangeCanTakeDamage());
            }
        }
    }

    private void Die()
    {
        PlayerController.BlockMovement?.Invoke(true);
        StartCoroutine(RestartSceneAfterDie());
    }
    private IEnumerator RestartSceneAfterDie()
    {
        diePanel.DOFade(1, 1.5f);
        yield return new WaitForSeconds(1.5f);

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
    
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy") || collision.CompareTag("Boss"))
        {
            _playerStayInTrigger = true;
        }    
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy") || collision.CompareTag("Boss"))
        {
            _playerStayInTrigger = false;
        }
    }

    private IEnumerator ChangeCanTakeDamage()
    {
        for (int i = 0; i < partOfBodies.Length; i++)
        {
            partOfBodies[i].color = Color.red;
        }
        
        yield return new WaitForSeconds(1.4f);
        _canTakeDamage = true;
        
        for (int i = 0; i < partOfBodies.Length; i++)
        {
            partOfBodies[i].color = _defaultBodyColors[i];
        }
    }
}
