using System.Collections.Generic;
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 resumo executivo de decisão para fechamento: headline, resumo curto, razões, riscos, conclusões, mensagem final e próxima ação.
    /// </summary>
    public class ProposalDecisionSummaryView : MonoBehaviour
    {
        private const string Title = "Resumo Executivo / Fechamento";
        private const string NenhumProjeto = "Nenhum projeto.";
        private const string HeadlineLabel = "Manchete: ";
        private const string ResumoCurto = "Resumo: ";
        private const string RazoesDecisao = "Principais razões da decisão: ";
        private const string Riscos = "Riscos-chave: ";
        private const string Orcamento = "Orçamento: ";
        private const string Experiencia = "Experiência: ";
        private const string Operacional = "Operacional: ";
        private const string MensagemVenda = "Mensagem final de venda: ";
        private const string ProximaAcao = "Próxima ação: ";
        private const string Prontidao = "Prontidão para decisão: ";

        private AppSession _session;
        private IProposalDecisionSummaryService _decisionService;
        private Transform _contentRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _decisionService = ServiceRegistry.Instance.Get<IProposalDecisionSummaryService>();
            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 = 400;
            var vlg = _contentRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            vlg.spacing = 6;
            vlg.childForceExpandHeight = false;
            vlg.childForceExpandWidth = true;
        }

        private void UpdateContent()
        {
            ClearChildren(_contentRoot);

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

            var summary = _decisionService?.Generate(project);
            if (summary == null)
            {
                AppendText(_contentRoot, "Não foi possível gerar o resumo executivo.");
                return;
            }

            project.LastDecisionSummary = summary;

            if (!string.IsNullOrEmpty(summary.ExecutiveHeadline))
                AppendText(_contentRoot, HeadlineLabel + summary.ExecutiveHeadline);
            if (!string.IsNullOrEmpty(summary.ExecutiveShortSummary))
                AppendText(_contentRoot, ResumoCurto + summary.ExecutiveShortSummary);

            AppendText(_contentRoot, Prontidao + ReadinessLevelText(summary.DecisionReadinessLevel));

            if (summary.MainDecisionReasons != null && summary.MainDecisionReasons.Count > 0)
            {
                AppendText(_contentRoot, RazoesDecisao);
                foreach (var r in summary.MainDecisionReasons)
                    AppendText(_contentRoot, "  • " + r);
            }
            if (summary.KeyRisks != null && summary.KeyRisks.Count > 0)
            {
                AppendText(_contentRoot, Riscos + string.Join("; ", summary.KeyRisks));
            }
            if (!string.IsNullOrEmpty(summary.BudgetConclusion))
                AppendText(_contentRoot, Orcamento + summary.BudgetConclusion);
            if (!string.IsNullOrEmpty(summary.ExperienceConclusion))
                AppendText(_contentRoot, Experiencia + summary.ExperienceConclusion);
            if (!string.IsNullOrEmpty(summary.OperationalConclusion))
                AppendText(_contentRoot, Operacional + summary.OperationalConclusion);
            if (!string.IsNullOrEmpty(summary.FinalSalesMessage))
                AppendText(_contentRoot, MensagemVenda + summary.FinalSalesMessage);
            if (!string.IsNullOrEmpty(summary.SuggestedNextAction))
                AppendText(_contentRoot, ProximaAcao + summary.SuggestedNextAction);
        }

        private static string ReadinessLevelText(ProposalDecisionReadinessLevel level)
        {
            switch (level)
            {
                case ProposalDecisionReadinessLevel.NotReady: return "Não pronto";
                case ProposalDecisionReadinessLevel.UnderReview: return "Em revisão";
                case ProposalDecisionReadinessLevel.ReadyToPresent: return "Pronto para apresentar";
                case ProposalDecisionReadinessLevel.ReadyToClose: return "Pronto para fechamento";
                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);
        }
    }
}
