using UnityEngine;
using UnityEngine.UI;
using TMPro;
using IStalk.Data;
using IStalk.Eye;

namespace IStalk.UI
{
    public class TrapSelectionUI : MonoBehaviour
    {
        [SerializeField] private Transform _slotContainer;
        [SerializeField] private GameObject _slotPrefab;
        [SerializeField] private EyeTrapPlacer _trapPlacer;
        [SerializeField] private TextMeshProUGUI _selectedTrapName;

        private TrapData_SO[] _allTraps;
        private int _selectedIndex;

        private void Start()
        {
            _allTraps = Resources.LoadAll<TrapData_SO>("Items/Traps");
            BuildSlots();
            SelectTrap(0);
        }

        private void Update()
        {
            for (int i = 0; i < Mathf.Min(_allTraps.Length, 9); i++)
            {
                if (Input.GetKeyDown(KeyCode.Alpha1 + i))
                {
                    SelectTrap(i);
                    break;
                }
            }

            float scroll = Input.mouseScrollDelta.y;
            if (Mathf.Abs(scroll) > 0.1f)
            {
                _selectedIndex += scroll > 0 ? -1 : 1;
                _selectedIndex = (_selectedIndex + _allTraps.Length) % _allTraps.Length;
                SelectTrap(_selectedIndex);
            }
        }

        private void BuildSlots()
        {
            foreach (Transform child in _slotContainer)
                Destroy(child.gameObject);

            for (int i = 0; i < _allTraps.Length; i++)
            {
                var slot = Instantiate(_slotPrefab, _slotContainer);
                var nameText = slot.GetComponentInChildren<TextMeshProUGUI>();
                if (nameText != null)
                    nameText.text = $"{i + 1}: {_allTraps[i].displayName}";

                var icon = slot.transform.Find("Icon")?.GetComponent<Image>();
                if (icon != null && _allTraps[i].eyeHudIcon != null)
                    icon.sprite = _allTraps[i].eyeHudIcon;

                int idx = i;
                var btn = slot.GetComponent<Button>();
                if (btn != null)
                    btn.onClick.AddListener(() => SelectTrap(idx));
            }
        }

        private void SelectTrap(int index)
        {
            if (_allTraps.Length == 0) return;
            _selectedIndex = Mathf.Clamp(index, 0, _allTraps.Length - 1);

            if (_trapPlacer != null)
                _trapPlacer.SelectTrap(_allTraps[_selectedIndex]);

            if (_selectedTrapName != null)
                _selectedTrapName.text = $"{_allTraps[_selectedIndex].displayName} (Cost: {_allTraps[_selectedIndex].dreadCost})";
        }
    }
}
