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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe a lista de fornecedores; permite selecionar (toggle) e destaca os selecionados.
    /// Estrutura preparada para futura filtragem por categoria, espaco e template.
    /// </summary>
    public class SupplierListView : MonoBehaviour, IHasContentRoot
    {
        private static readonly Color NormalColor = Color.white;
        private static readonly Color SelectedColor = new Color(1f, 0.9f, 0.4f);
        /// <summary>Destaque para fornecedor principal do template selecionado (contextual).</summary>
        private static readonly Color TemplatePrincipalColor = new Color(0.6f, 0.85f, 1f, 1f);
        private const string SuffixPrincipalTemplate = " (principal no template)";

        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;
        }

        private const string HintContextual = "(Listagem geral — filtro por categoria/espaço/template em preparação)";

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

            ClearContent(_content);

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

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

            var templatePrincipalId = _session?.SelectedTemplate?.SupplierId;
            foreach (var supplier in service.GetAll())
            {
                CreateItem(_content, supplier, font, templatePrincipalId);
            }

            RefreshSelectionHighlight();
        }

        private static void CreateHintRow(Transform parent, Font font)
        {
            var go = new GameObject("Hint");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 18);
            var text = go.AddComponent<Text>();
            text.text = HintContextual;
            text.font = font;
            text.fontSize = 12;
            text.color = new Color(0.45f, 0.45f, 0.45f, 1f);
        }

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

            var selectedIds = _session.SelectedSupplierIds;
            var templatePrincipalId = _session.SelectedTemplate?.SupplierId;

            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)
                {
                    var selected = selectedIds != null && selectedIds.Contains(item.Id);
                    if (selected)
                        text.color = SelectedColor;
                    else if (item.Id == templatePrincipalId)
                        text.color = TemplatePrincipalColor;
                    else
                        text.color = 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, Supplier supplier, Font font, string templatePrincipalId)
        {
            var go = new GameObject("SupplierItem");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 24);

            var isPrincipal = supplier.Id == templatePrincipalId;
            var displayText = $"{supplier.Name} — {supplier.Description}";
            if (isPrincipal)
                displayText += SuffixPrincipalTemplate;

            var text = go.AddComponent<Text>();
            text.text = displayText;
            text.font = font;
            text.fontSize = 16;

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

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