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 roteiro guiado da proposta: ordem, título, descrição, foco, duração sugerida, mensagem comercial e momento-chave.
    /// </summary>
    public class ProposalGuidedTourView : MonoBehaviour
    {
        private const string Title = "Roteiro Guiado / Apresentação ao Cliente";
        private const string NenhumProjeto = "Nenhum projeto ou proposta ativa.";
        private const string Duracao = "Duração: ";
        private const string MensagemComercial = "Mensagem: ";
        private const string MomentoChave = " [Momento-chave]";
        private const string NenhumPasso = "Nenhum passo no roteiro. Gere a narrativa e os momentos para estruturar o roteiro.";

        private AppSession _session;
        private IProposalGuidedTourService _guidedTourService;
        private Transform _contentRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _guidedTourService = ServiceRegistry.Instance.Get<IProposalGuidedTourService>();
            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 = 320;
            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 tourSteps = _guidedTourService?.GenerateGuidedTour(project, active);
            if (tourSteps == null || tourSteps.Count == 0)
            {
                AppendText(_contentRoot, NenhumPasso);
                return;
            }

            active.GuidedTourSteps = new List<ProposalGuidedTourStep>(tourSteps);

            foreach (var step in tourSteps.OrderBy(s => s.DisplayOrder))
            {
                var card = new GameObject("StepCard");
                card.transform.SetParent(_contentRoot, false);
                card.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 62);
                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.96f, 0.97f, 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 = (step.DisplayOrder + 1) + ". " + (step.Title ?? "Passo") + (step.IsKeyMoment ? MomentoChave : "") + " — " + FocusTypeText(step.FocusType) + " | " + Duracao + step.SuggestedDurationMinutes + " min";
                titleText.font = _font;
                titleText.fontSize = 13;
                titleText.fontStyle = FontStyle.Bold;

                if (!string.IsNullOrEmpty(step.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 = step.Description;
                    descText.font = _font;
                    descText.fontSize = 11;
                    descText.color = new Color(0.35f, 0.35f, 0.4f, 1f);
                }

                if (!string.IsNullOrEmpty(step.SalesMessage))
                {
                    var salesLine = new GameObject("Sales");
                    salesLine.transform.SetParent(card.transform, false);
                    salesLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    var salesText = salesLine.AddComponent<Text>();
                    salesText.text = MensagemComercial + step.SalesMessage;
                    salesText.font = _font;
                    salesText.fontSize = 10;
                    salesText.color = new Color(0.25f, 0.45f, 0.3f, 1f);
                }
            }
        }

        private static string FocusTypeText(ProposalGuidedTourFocusType focus)
        {
            switch (focus)
            {
                case ProposalGuidedTourFocusType.Welcome: return "Boas-vindas";
                case ProposalGuidedTourFocusType.SpaceOverview: return "Visão do espaço";
                case ProposalGuidedTourFocusType.ThemeHighlight: return "Tema";
                case ProposalGuidedTourFocusType.MomentHighlight: return "Momento";
                case ProposalGuidedTourFocusType.SupplierHighlight: return "Fornecedores";
                case ProposalGuidedTourFocusType.PremiumUpsell: return "Upgrade";
                case ProposalGuidedTourFocusType.OperationalConfidence: return "Operação";
                case ProposalGuidedTourFocusType.Closing: 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 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);
        }
    }
}
