using TMPro;
using UnityEngine;

public class PeopleManager : MonoBehaviour
{
    [Header("Displays")]
    [SerializeField] private TextMeshProUGUI peopleTotalText;
    [SerializeField] private TextMeshProUGUI foodTotalText;
    [SerializeField] private TextMeshProUGUI homesTotalText;

    #region Stats
    private int peopleCount = 0;
    public int PeopleCount
    {
        get => peopleCount;
        set
        {
            peopleCount = value;
            peopleTotalText.text = peopleCount.ToString();
        }
    }

    private int foodCount = 0;
    public int FoodCount
    {
        get => foodCount;
        set
        {
            foodCount = value;
            foodTotalText.text = foodCount.ToString();
        }
    }

    private int homeCount = 0;
    public int HomeCount
    {
        get => homeCount;
        set
        {
            homeCount = value;
            homesTotalText.text = homeCount.ToString();
        }
    }
    #endregion

    public int MissingHousing { get; private set; }
    public int FoodEaten { get; private set; }
    public int MissingFood { get; private set; }
    public int PeopleLeaving { get; private set; }


    public static PeopleManager Instance;
    private void Awake()
    {
        if (Instance == null) Instance = this;
        else Destroy(gameObject);

        MissingHousing = 0;
        FoodEaten = 0;
        MissingFood = 0;
        PeopleLeaving = 0;

        peopleTotalText.text = peopleCount.ToString();
        foodTotalText.text = foodCount.ToString();
        homesTotalText.text = homeCount.ToString();

        Events.OnAddPeople += OnAddPeople;
        Events.OnRemovePeople += OnRemovePeople;

        Events.OnAddHome += OnAddHome;
        Events.OnRemoveHome += OnRemoveHome;

        Events.OnDayStart += OnDayStart;
    }

    private void OnDestroy()
    {
        Events.OnAddPeople -= OnAddPeople;
        Events.OnRemovePeople -= OnRemovePeople;

        Events.OnAddHome -= OnAddHome;
        Events.OnRemoveHome -= OnRemoveHome;
        Events.OnDayStart -= OnDayStart;
    }

    private void OnAddPeople(int amount) => PeopleCount += amount;
    private void OnRemovePeople(int amount) => PeopleCount -= amount;
    private void OnAddHome(int amount) => HomeCount += amount;
    private void OnRemoveHome(int amount) => HomeCount -= amount;

    public void CalculateMissingStats()
    {
        MissingHousing = Mathf.Max(0, peopleCount - homeCount);
        FoodEaten = Mathf.Min(peopleCount, foodCount);
        MissingFood = Mathf.Max(0, peopleCount - foodCount);
        PeopleLeaving = Mathf.Max(MissingFood, MissingHousing);
    }

    private void OnDayStart()
    {
        Events.RemoveCards(CardType.Food, FoodEaten);
        if (PeopleLeaving > 0)
        {
            Events.RemoveCards(CardType.Person, PeopleLeaving);
            Events.RemovePeople(PeopleLeaving);
        }
        
        if (PeopleCount <= 0)
            Events.GameEnd();
    }
}
