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 o plano de apresentação para Quest 3 / realidade mista: modo, título, sequência guiada, hotspots, estados de cena, zonas prioritárias, momentos-chave, duração, objetivo e prontidão MR.
    /// </summary>
    public class MRPresentationPlanView : MonoBehaviour
    {
        private const string Title = "Plano Quest / Apresentação em Realidade Mista";
        private const string NenhumProjeto = "Nenhum projeto.";
        private const string ModoLabel = "Modo de apresentação: ";
        private const string TituloLabel = "Título: ";
        private const string SequenciaLabel = "Sequência guiada (passos): ";
        private const string HotspotsLabel = "Hotspots usados: ";
        private const string EstadosCenaLabel = "Estados de cena: ";
        private const string ZonasLabel = "Zonas prioritárias: ";
        private const string MomentosLabel = "Momentos-chave de venda: ";
        private const string DuracaoLabel = "Duração recomendada: ";
        private const string ObjetivoLabel = "Objetivo executivo: ";
        private const string ProntidaoLabel = "Pronto para mapeamento MR: ";

        private AppSession _session;
        private IMRPresentationPlanningService _planningService;
        private Transform _contentRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _planningService = ServiceRegistry.Instance.Get<IMRPresentationPlanningService>();
            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 = 380;
            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 proposal = project?.GetActiveProposal();
            if (project == null || proposal == null)
            {
                AppendText(_contentRoot, NenhumProjeto);
                return;
            }

            var plan = _planningService?.GeneratePlan(project, proposal);
            if (plan == null)
            {
                AppendText(_contentRoot, "Não foi possível gerar o plano de apresentação MR.");
                return;
            }

            proposal.MRPresentationPlan = plan;

            AppendText(_contentRoot, ModoLabel + TargetModeText(plan.TargetExperienceMode));
            if (!string.IsNullOrEmpty(plan.PresentationTitle))
                AppendText(_contentRoot, TituloLabel + plan.PresentationTitle);

            AppendText(_contentRoot, ProntidaoLabel + (plan.ReadyForMRMapping ? "Sim" : "Não"));

            if (plan.GuidedSequenceStepIds != null && plan.GuidedSequenceStepIds.Count > 0)
                AppendText(_contentRoot, SequenciaLabel + plan.GuidedSequenceStepIds.Count + " passos");
            if (plan.HotspotIds != null && plan.HotspotIds.Count > 0)
                AppendText(_contentRoot, HotspotsLabel + plan.HotspotIds.Count);
            if (plan.SceneStateIds != null && plan.SceneStateIds.Count > 0)
                AppendText(_contentRoot, EstadosCenaLabel + plan.SceneStateIds.Count);

            if (plan.PriorityZones != null && plan.PriorityZones.Count > 0)
                AppendText(_contentRoot, ZonasLabel + string.Join(", ", plan.PriorityZones));
            if (plan.KeySellingMoments != null && plan.KeySellingMoments.Count > 0)
            {
                AppendText(_contentRoot, MomentosLabel);
                foreach (var m in plan.KeySellingMoments.Take(5))
                    AppendText(_contentRoot, "  • " + m);
            }

            if (plan.RecommendedSessionDurationMinutes > 0)
                AppendText(_contentRoot, DuracaoLabel + plan.RecommendedSessionDurationMinutes + " min");
            if (!string.IsNullOrEmpty(plan.ExecutivePresentationGoal))
                AppendText(_contentRoot, ObjetivoLabel + plan.ExecutivePresentationGoal);
        }

        private static string TargetModeText(MRPresentationTargetMode mode)
        {
            switch (mode)
            {
                case MRPresentationTargetMode.GuidedSalesTour: return "Tour de venda guiado";
                case MRPresentationTargetMode.FreeExploration: return "Exploração livre";
                case MRPresentationTargetMode.SideBySideComparison: return "Comparação lado a lado";
                case MRPresentationTargetMode.ExecutiveClosingMode: return "Fechamento executivo";
                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 t = go.AddComponent<Text>();
            t.text = text;
            t.font = _font;
            t.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);
        }
    }
}
