using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe templates de evento relacionados à categoria selecionada; permite selecionar um e destaca o selecionado.
    /// Se nenhuma categoria estiver selecionada, exibe todos. Estrutura preparada para regras mais avançadas.
    /// </summary>
    public class EventTemplateListView : MonoBehaviour, IHasContentRoot
    {
        private static readonly Color NormalColor = Color.white;
        private static readonly Color SelectedColor = new Color(1f, 0.9f, 0.4f);
        private const string MessageSelectCategory = "Selecione uma categoria para filtrar os modelos.";

        private Transform _content;
        private AppSession _session;
        private Text _placeholderText;

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

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

            Refresh();
        }

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

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

            ClearContent(_content);
            DestroyPlaceholder();

            var templateService = ServiceRegistry.Instance.Get<ITemplateService>();
            if (templateService == null) return;

            IReadOnlyList<EventTemplate> templates;
            if (!string.IsNullOrEmpty(_session?.SelectedCategoryId))
                templates = templateService.GetByCategoryId(_session.SelectedCategoryId);
            else
                templates = templateService.GetAll();

            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

            if (templates == null || templates.Count == 0)
            {
                ShowPlaceholder(_session?.SelectedCategoryId == null ? MessageSelectCategory : "Nenhum modelo para esta categoria.", font);
                return;
            }

            foreach (var template in templates)
                CreateItem(_content, template, font);

            RefreshSelectionHighlight();
        }

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

            var selectedId = _session.SelectedTemplateId;
            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 void ShowPlaceholder(string message, Font font)
        {
            var go = new GameObject("Placeholder");
            go.transform.SetParent(_content, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 24);
            _placeholderText = go.AddComponent<Text>();
            _placeholderText.text = message;
            _placeholderText.font = font;
            _placeholderText.fontSize = 14;
            _placeholderText.color = new Color(0.5f, 0.5f, 0.5f, 1f);
        }

        private void DestroyPlaceholder()
        {
            if (_placeholderText != null && _placeholderText.gameObject != null)
            {
                Destroy(_placeholderText.gameObject);
                _placeholderText = null;
            }
        }

        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, EventTemplate template, Font font)
        {
            var go = new GameObject("TemplateItem");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 24);

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

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

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