using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using YachtDice.Modifiers.Runtime;

namespace YachtDice.Inventory
{
    public class InventoryView : MonoBehaviour
    {
        [SerializeField] private Transform slotContainer;
        [SerializeField] private InventorySlotView slotPrefab;
        [SerializeField] private TMP_Text slotCountText;
        [SerializeField] private Button closeButton;

        private readonly List<InventorySlotView> spawnedSlots = new();

        public event Action<ModifierInstance> OnActivateClicked;
        public event Action<ModifierInstance> OnDeactivateClicked;
        public event Action<ModifierInstance> OnSellClicked;

        private void Awake()
        {
            if (closeButton != null)
                closeButton.onClick.AddListener(Hide);
        }

        private void OnDestroy()
        {
            if (closeButton != null)
                closeButton.onClick.RemoveListener(Hide);
        }

        public void Show() => gameObject.SetActive(true);
        public void Hide() => gameObject.SetActive(false);
        public bool IsVisible => gameObject.activeSelf;

        public void Refresh(IReadOnlyList<ModifierInstance> owned, int maxSlots)
        {
            ClearSlots();

            int activeCount = 0;

            for (int i = 0; i < owned.Count; i++)
            {
                var inst = owned[i];
                if (inst.IsActive) activeCount++;

                var slot = Instantiate(slotPrefab, slotContainer);
                slot.Setup(inst, activeCount <= maxSlots);
                slot.OnActivateClicked += HandleActivate;
                slot.OnDeactivateClicked += HandleDeactivate;
                slot.OnSellClicked += HandleSell;
                spawnedSlots.Add(slot);
            }

            if (slotCountText != null)
                slotCountText.text = $"{activeCount}/{maxSlots}";
        }

        private void ClearSlots()
        {
            for (int i = 0; i < spawnedSlots.Count; i++)
            {
                spawnedSlots[i].OnActivateClicked -= HandleActivate;
                spawnedSlots[i].OnDeactivateClicked -= HandleDeactivate;
                spawnedSlots[i].OnSellClicked -= HandleSell;
                Destroy(spawnedSlots[i].gameObject);
            }
            spawnedSlots.Clear();
        }

        private void HandleActivate(ModifierInstance inst) => OnActivateClicked?.Invoke(inst);
        private void HandleDeactivate(ModifierInstance inst) => OnDeactivateClicked?.Invoke(inst);
        private void HandleSell(ModifierInstance inst) => OnSellClicked?.Invoke(inst);
    }
}
