using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe a lista de espacos; permite selecionar um e destaca o selecionado.
    /// </summary>
    public class SpaceListView : MonoBehaviour, IHasContentRoot
    {
        private static readonly Color NormalColor = Color.white;
        private static readonly Color SelectedColor = new Color(1f, 0.9f, 0.4f);

        private Transform _content;
        private AppSession _session;

        public void SetContentRoot(Transform contentRoot)
        {
            _content = contentRoot;
        }

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            if (_session != null)
                _session.OnSessionChanged += RefreshSelectionHighlight;

            Refresh();
        }

        private void OnDestroy()
        {
            if (_session != null)
                _session.OnSessionChanged -= RefreshSelectionHighlight;
        }

        public void Refresh()
        {
            if (_content == null) return; // Content root atribuido via SetContentRoot

            ClearContent(_content);

            var service = ServiceRegistry.Instance.Get<ISpaceService>();
            if (service == null) return;

            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            foreach (var space in service.GetAll())
            {
                CreateItem(_content, space, font);
            }

            RefreshSelectionHighlight();
        }

        public void RefreshSelectionHighlight()
        {
            if (_content == null || _session == null) return;

            var selectedId = _session.SelectedSpaceId;
            for (var i = 0; i < _content.childCount; i++)
            {
                var child = _content.GetChild(i);
                var item = child.GetComponent<SelectableListItem>();
                var text = child.GetComponent<Text>();
                if (item != null && text != null)
                    text.color = item.Id == selectedId ? SelectedColor : NormalColor;
            }
        }

        private static void ClearContent(Transform content)
        {
            for (var i = content.childCount - 1; i >= 0; i--)
                Destroy(content.GetChild(i).gameObject);
        }

        private void CreateItem(Transform parent, Space space, Font font)
        {
            var go = new GameObject("SpaceItem");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 24);

            var text = go.AddComponent<Text>();
            text.text = $"{space.Name} — {space.Description} (cap. {space.Capacity})";
            text.font = font;
            text.fontSize = 16;

            var selectable = go.AddComponent<SelectableListItem>();
            selectable.Id = space.Id;

            var button = go.AddComponent<Button>();
            button.targetGraphic = text;
            button.onClick.AddListener(() =>
            {
                if (_session != null)
                    _session.SelectedSpace = space;
            });
        }
    }
}
