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 a narrativa de apresentação comercial da proposta (etapas em ordem).
    /// Permite gerar ou regenerar a narrativa. Usa referências explícitas a containers (sem Find por nome).
    /// </summary>
    public class ProposalPresentationView : MonoBehaviour
    {
        private const string Title = "Apresentação Comercial / Narrativa da Proposta";
        private const string NenhumProjeto = "Nenhum projeto iniciado. Inicie um projeto para gerar a narrativa.";
        private const string GerarNarrativa = "Gerar narrativa da proposta";
        private const string RegenerarNarrativa = "Regenerar narrativa";
        private const string Destaque = "Destaque";
        private const string OrdemFmt = "Etapa {0}";

        private AppSession _session;
        private Transform _stepsRoot;
        private Text _generateButtonText;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            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 = 8;
                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;

            var buttonGo = new GameObject("GenerateButton");
            buttonGo.transform.SetParent(transform, false);
            buttonGo.AddComponent<RectTransform>().sizeDelta = new Vector2(200, 28);
            var buttonLE = buttonGo.AddComponent<LayoutElement>();
            buttonLE.preferredWidth = 200;
            buttonLE.preferredHeight = 28;
            var button = buttonGo.AddComponent<Button>();
            buttonGo.AddComponent<Image>().color = new Color(0.45f, 0.5f, 0.7f, 1f);
            var buttonTextGo = new GameObject("Text");
            buttonTextGo.transform.SetParent(buttonGo.transform, false);
            var buttonTextRt = buttonTextGo.AddComponent<RectTransform>();
            buttonTextRt.anchorMin = Vector2.zero;
            buttonTextRt.anchorMax = Vector2.one;
            buttonTextRt.offsetMin = Vector2.zero;
            buttonTextRt.offsetMax = Vector2.zero;
            var buttonText = buttonTextGo.AddComponent<Text>();
            buttonText.text = GerarNarrativa;
            buttonText.font = _font;
            buttonText.fontSize = 13;
            buttonText.alignment = TextAnchor.MiddleCenter;
            buttonText.color = Color.white;
            _generateButtonText = buttonText;
            button.onClick.AddListener(OnGenerateClicked);

            _stepsRoot = new GameObject("StepsRoot").transform;
            _stepsRoot.SetParent(transform, false);
            var stepsLE = _stepsRoot.gameObject.AddComponent<LayoutElement>();
            stepsLE.preferredHeight = 220;
            var stepsVlg = _stepsRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            stepsVlg.spacing = 6;
            stepsVlg.childForceExpandHeight = false;
            stepsVlg.childForceExpandWidth = true;
        }

        private void OnGenerateClicked()
        {
            _session?.GeneratePresentation();
        }

        private void UpdateContent()
        {
            ClearChildren(_stepsRoot);

            var project = _session?.CurrentProject;
            if (project == null)
            {
                if (_generateButtonText != null) _generateButtonText.text = GerarNarrativa;
                AppendText(_stepsRoot, NenhumProjeto);
                return;
            }

            var steps = project.GeneratedPresentationSteps;
            if (_generateButtonText != null)
                _generateButtonText.text = (steps != null && steps.Count > 0) ? RegenerarNarrativa : GerarNarrativa;
            if (steps == null || steps.Count == 0)
            {
                AppendText(_stepsRoot, "Clique em \"" + GerarNarrativa + "\" para criar a sequência de apresentação.");
                return;
            }

            for (var i = 0; i < steps.Count; i++)
            {
                var step = steps[i];
                var orderLabel = string.Format(OrdemFmt, i + 1);
                AppendStepBlock(_stepsRoot, step, orderLabel);
            }
        }

        private void AppendStepBlock(Transform parent, ProposalPresentationStep step, string orderLabel)
        {
            var block = new GameObject($"Step_{step.Id}");
            block.transform.SetParent(parent, false);
            var blockVlg = block.AddComponent<VerticalLayoutGroup>();
            blockVlg.spacing = 2;
            blockVlg.padding = new RectOffset(8, 6, 6, 6);
            blockVlg.childForceExpandHeight = false;
            blockVlg.childForceExpandWidth = true;
            block.AddComponent<Image>().color = step.IsHighlight ? new Color(0.95f, 0.94f, 0.88f, 1f) : new Color(1f, 1f, 1f, 0.6f);

            var line1 = new GameObject("Line1");
            line1.transform.SetParent(block.transform, false);
            var line1Hlg = line1.AddComponent<HorizontalLayoutGroup>();
            line1Hlg.spacing = 8;
            line1Hlg.childForceExpandWidth = false;
            line1Hlg.childForceExpandHeight = true;
            line1.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

            var orderGo = new GameObject("Order");
            orderGo.transform.SetParent(line1.transform, false);
            orderGo.AddComponent<RectTransform>().sizeDelta = new Vector2(70, 18);
            var orderLE = orderGo.AddComponent<LayoutElement>();
            orderLE.preferredWidth = 70;
            var orderText = orderGo.AddComponent<Text>();
            orderText.text = orderLabel;
            orderText.font = _font;
            orderText.fontSize = 12;
            orderText.color = new Color(0.35f, 0.35f, 0.35f, 1f);

            var titleGo = new GameObject("Title");
            titleGo.transform.SetParent(line1.transform, false);
            titleGo.AddComponent<RectTransform>().sizeDelta = new Vector2(200, 18);
            var titleLE = titleGo.AddComponent<LayoutElement>();
            titleLE.preferredWidth = 200;
            titleLE.flexibleWidth = 1;
            var titleText = titleGo.AddComponent<Text>();
            titleText.text = step.Title ?? "";
            titleText.font = _font;
            titleText.fontSize = 14;
            titleText.fontStyle = FontStyle.Bold;

            if (step.IsHighlight)
            {
                var badgeGo = new GameObject("HighlightBadge");
                badgeGo.transform.SetParent(line1.transform, false);
                badgeGo.AddComponent<RectTransform>().sizeDelta = new Vector2(52, 16);
                var badgeLE = badgeGo.AddComponent<LayoutElement>();
                badgeLE.preferredWidth = 52;
                badgeLE.preferredHeight = 16;
                var badgeText = badgeGo.AddComponent<Text>();
                badgeText.text = Destaque;
                badgeText.font = _font;
                badgeText.fontSize = 10;
                badgeText.fontStyle = FontStyle.Bold;
                badgeText.color = new Color(0.4f, 0.35f, 0.2f, 1f);
            }

            if (!string.IsNullOrEmpty(step.Description))
            {
                var descGo = new GameObject("Description");
                descGo.transform.SetParent(block.transform, false);
                descGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                var descText = descGo.AddComponent<Text>();
                descText.text = step.Description;
                descText.font = _font;
                descText.fontSize = 11;
                descText.color = new Color(0.25f, 0.25f, 0.25f, 1f);
            }
        }

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

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