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

public class CardHoldArea : MonoBehaviour
{
    [SerializeField] protected bool stackCards = false;
    [SerializeField] protected GameObject cardSlots;
    [SerializeField] protected TextMeshProUGUI countDisplay;
    [SerializeField] protected TextMeshProUGUI maxCountDisplay;

    public ICardHolder cardHolder;
    protected List<Card> cards = new();
    protected bool displayCount = false;

    private void Start()
    {
        if (countDisplay != null)
        {
            displayCount = true;
            countDisplay.text = cards.Count.ToString();
            maxCountDisplay.text = "/" + cardSlots.transform.childCount.ToString();
        }
    }

    public bool IsEmptySlot()
    {
        return cards.Count < cardSlots.transform.childCount || stackCards;
    }

    public virtual bool CanAddCard(Card card)
    {
        return cardHolder.CanAddCard(card.cardData) &&
            IsEmptySlot() &&
            !cards.Contains(card);
    }

    public virtual void AddCard(Card card) 
    {
        cardHolder.AddCard(card.cardData);
        Transform slot = GetCardSlot();
        card.transform.parent = slot;
        card.transform.position = slot.position;
        cards.Add(card);
        if (displayCount) countDisplay.text = cards.Count.ToString();
        

        Transform GetCardSlot()
        {
            if (stackCards) return cardSlots.transform.GetChild(0);
            for (int i = 0; i < cardSlots.transform.childCount; i++)
            {
                Transform child = cardSlots.transform.GetChild(i);
                if (child.childCount == 0)
                    return child;
            }
            return null;
        }
    }

    public virtual void RemoveCard(Card card)
    {
        if (cards.Contains(card))
        {
            cards.Remove(card);
            cardHolder.RemoveCard(card.cardData);
            if (displayCount) countDisplay.text = cards.Count.ToString();
        }
    }

    public void DropCards()
    {
        Building building;
        if (cardHolder is Building build)
            building = build;
        else
            building = (cardHolder as BuildingBuilder).transform.parent.gameObject.GetComponent<Building>();

        Vector2 corner = MapManager.Instance.CalcCorner(building.transform.position, building.BuildingData.Size);

        for (int i = cards.Count-1; i >= 0; i--)
        {
            cards[i].transform.position = corner;
            Events.PlaceCard(cards[i]);
            corner.x += 1;
        }
    }

    public Card GetCard()
    {
        return cards.Count > 0 ? cards[^1] : null;
    }
}