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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe hotspots/pontos de destaque visuais: prioridade, título, descrição, tipo, zonas/itens, valor comercial, duração e upsell premium.
    /// </summary>
    public class ProposalVisualHotspotView : MonoBehaviour
    {
        private const string Title = "Hotspots Visuais / Pontos de Destaque";
        private const string NenhumProjeto = "Nenhum projeto ou proposta ativa.";
        private const string Prioridade = "Prioridade: ";
        private const string ValorComercial = "Valor comercial: ";
        private const string Foco = "Foco: ";
        private const string UpsellPremium = " [Upsell premium]";
        private const string NenhumHotspot = "Nenhum hotspot. Gere o roteiro guiado para estruturar os pontos de destaque.";

        private AppSession _session;
        private IProposalVisualHotspotService _hotspotService;
        private Transform _contentRoot;
        private Font _font;

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

            _font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            BuildUI();
            UpdateContent();
        }

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

        private void BuildUI()
        {
            var layout = gameObject.GetComponent<VerticalLayoutGroup>();
            if (layout == null)
            {
                layout = gameObject.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 6;
                layout.padding = new RectOffset(12, 12, 12, 12);
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;
            }

            var titleGo = new GameObject("Title");
            titleGo.transform.SetParent(transform, false);
            titleGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var titleText = titleGo.AddComponent<Text>();
            titleText.text = Title;
            titleText.font = _font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            _contentRoot = new GameObject("ContentRoot").transform;
            _contentRoot.SetParent(transform, false);
            _contentRoot.gameObject.AddComponent<LayoutElement>().preferredHeight = 300;
            var vlg = _contentRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            vlg.spacing = 6;
            vlg.childForceExpandHeight = false;
            vlg.childForceExpandWidth = true;
        }

        private void UpdateContent()
        {
            ClearChildren(_contentRoot);

            var project = _session?.CurrentProject;
            var active = project?.GetActiveProposal();
            if (project == null || active == null)
            {
                AppendText(_contentRoot, NenhumProjeto);
                return;
            }

            var list = _hotspotService?.GenerateHotspots(project, active);
            if (list == null || list.Count == 0)
            {
                AppendText(_contentRoot, NenhumHotspot);
                return;
            }

            active.VisualHotspots = new List<ProposalVisualHotspot>(list);

            foreach (var h in list.OrderBy(x => x.HighlightPriority))
            {
                var card = new GameObject("HotspotCard");
                card.transform.SetParent(_contentRoot, false);
                card.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 58);
                var cardVlg = card.AddComponent<VerticalLayoutGroup>();
                cardVlg.spacing = 2;
                cardVlg.padding = new RectOffset(8, 8, 8, 8);
                cardVlg.childForceExpandHeight = false;
                cardVlg.childForceExpandWidth = true;
                card.AddComponent<Image>().color = new Color(0.97f, 0.96f, 0.95f, 1f);

                var titleLine = new GameObject("Title");
                titleLine.transform.SetParent(card.transform, false);
                titleLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                var titleText = titleLine.AddComponent<Text>();
                titleText.text = Prioridade + h.HighlightPriority + " — " + (h.Title ?? "Destaque") + (h.IsPremiumUpsell ? UpsellPremium : "") + " | " + HotspotTypeText(h.HotspotType) + " | " + ValorComercial + h.SalesValueScore + " | " + Foco + h.SuggestedFocusDurationMinutes + " min";
                titleText.font = _font;
                titleText.fontSize = 13;
                titleText.fontStyle = FontStyle.Bold;

                if (!string.IsNullOrEmpty(h.Description))
                {
                    var descLine = new GameObject("Desc");
                    descLine.transform.SetParent(card.transform, false);
                    descLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    var descText = descLine.AddComponent<Text>();
                    descText.text = h.Description;
                    descText.font = _font;
                    descText.fontSize = 11;
                    descText.color = new Color(0.35f, 0.35f, 0.4f, 1f);
                }

                if ((h.RelatedZoneTypes?.Count ?? 0) > 0 || (h.RelatedShowroomItemIds?.Count ?? 0) > 0)
                {
                    var detailLine = new GameObject("Detail");
                    detailLine.transform.SetParent(card.transform, false);
                    detailLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 12);
                    var detailText = detailLine.AddComponent<Text>();
                    var parts = new List<string>();
                    if (h.RelatedZoneTypes?.Count > 0) parts.Add("Zonas: " + string.Join(", ", h.RelatedZoneTypes));
                    if (h.RelatedShowroomItemIds?.Count > 0) parts.Add(h.RelatedShowroomItemIds.Count + " itens");
                    detailText.text = string.Join(" | ", parts);
                    detailText.font = _font;
                    detailText.fontSize = 10;
                    detailText.color = new Color(0.4f, 0.45f, 0.5f, 1f);
                }
            }
        }

        private static string HotspotTypeText(ProposalVisualHotspotType t)
        {
            switch (t)
            {
                case ProposalVisualHotspotType.EntranceImpact: return "Entrada";
                case ProposalVisualHotspotType.ThemeHighlight: return "Tema";
                case ProposalVisualHotspotType.PremiumDecor: return "Decoração premium";
                case ProposalVisualHotspotType.DiningExperience: return "Refeição";
                case ProposalVisualHotspotType.StageMoment: return "Palco";
                case ProposalVisualHotspotType.LoungeExperience: return "Lounge";
                case ProposalVisualHotspotType.SupplierShowcase: return "Fornecedores";
                case ProposalVisualHotspotType.OperationalConfidence: return "Operação";
                case ProposalVisualHotspotType.ClosingVisual: return "Encerramento";
                default: return "—";
            }
        }

        private void AppendText(Transform parent, string text)
        {
            var go = new GameObject("TextLine");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
            var line = go.AddComponent<Text>();
            line.text = text;
            line.font = _font;
            line.fontSize = 12;
        }

        private static void ClearChildren(Transform root)
        {
            if (root == null) return;
            for (var i = root.childCount - 1; i >= 0; i--)
                Object.Destroy(root.GetChild(i).gameObject);
        }
    }
}
