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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe a lista de categorias de evento; permite selecionar uma e destaca a selecionada.
    /// </summary>
    public class EventCategoryListView : 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 deve ser atribuido via SetContentRoot pelo controlador da cena

            ClearContent(_content);

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

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

            RefreshSelectionHighlight();
        }

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

            var selectedId = _session.SelectedCategoryId;
            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, EventCategory category, Font font)
        {
            var go = new GameObject("CategoryItem");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 24);

            var text = go.AddComponent<Text>();
            text.text = $"{category.DisplayName} — {category.Description}";
            text.font = font;
            text.fontSize = 16;

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

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