using System;
using System.Collections.Generic;
using UnityEngine;

public class PlayerManager : MonoBehaviour
{
    public GameObject playerPrefab;
    public UI_JoinButton joingButton;

    public static event Action OnPlayerRespawn;
    public static event Action OnPlayerDeath;

    public static PlayerManager instance;

    public List<GameObject> objectsToDisable;


    public int lifePoints;
    public int maxPlayerCount = 1;
    public int playerCountWinCondition;
    [Header("Player")]
    [SerializeField] private Transform respawnPoint;

    private void Awake()
    {
        DontDestroyOnLoad(this.gameObject);

        if (instance == null)
            instance = this;
        else
            Destroy(this.gameObject);
    }

    public void EnableJoinAndUpdateLifePoints()
    {
        playerCountWinCondition = maxPlayerCount;
        lifePoints = maxPlayerCount;
        joingButton = FindFirstObjectByType<UI_JoinButton>();
        UI_InGame.instance.UpdateLifePointsUI(lifePoints, maxPlayerCount);
    }

    public void AddPlayer()
    {

        GameObject newPlayer = Instantiate(playerPrefab);
        Player player = newPlayer.GetComponent<Player>();


        OnPlayerRespawn?.Invoke();
        PlaceNewPlayerAtRespawnPoint(player.transform);

        int newPlayerSkinId = SkinManager.instance.GetSkinId(0);

        player.UpdateSkin(newPlayerSkinId);

        foreach (GameObject gameObject in objectsToDisable)
        {
            if (gameObject != null)
                gameObject.SetActive(false);
        }
    }

    public void RemovePlayer(Player player)
    {

        GameManager.instance.RestartLevel();

        UI_InGame.instance.UpdateLifePointsUI(lifePoints, maxPlayerCount);
        joingButton.gameObject.SetActive(true);
        OnPlayerDeath?.Invoke();
    }

    private bool CanRemoveLifePoints()
    {
        if (DifficultyManager.instance.difficulty == DifficultyType.Hard)
        {
            return true;
        }


        if (GameManager.instance.fruitsCollected <= 0 && DifficultyManager.instance.difficulty == DifficultyType.Normal)
        {
            return true;
        }

        return false;
    }


    public List<Player> GetPlayerList() => playerList;

    public void UpdateRespawnPosition(Transform newRespawnPoint) => respawnPoint = newRespawnPoint;
    private void PlaceNewPlayerAtRespawnPoint(Transform newPlayer)
    {
        if (respawnPoint == null)
            respawnPoint = FindFirstObjectByType<StartPoint>().transform;


        newPlayer.position = respawnPoint.position;
    }
}
