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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe a recomendação executiva da melhor proposta: proposta recomendada, confiança, resumo, por que vence, tradeoffs, posicionamentos e segunda opção.
    /// </summary>
    public class ProposalRecommendationView : MonoBehaviour
    {
        private const string Title = "Recomendação Final / Melhor Proposta";
        private const string NenhumProjeto = "Nenhum projeto.";
        private const string NenhumaProposta = "Nenhuma proposta no projeto. Duplique ou crie propostas para gerar recomendação.";
        private const string PropostaRecomendada = "Proposta recomendada: ";
        private const string Confianca = "Confiança: ";
        private const string ResumoExecutivo = "Resumo executivo: ";
        private const string PorQueVence = "Por que vence: ";
        private const string TradeoffsLabel = "Tradeoffs: ";
        private const string Orcamento = "Orçamento: ";
        private const string Experiencia = "Experiência: ";
        private const string Operacional = "Operacional: ";
        private const string AnguloVenda = "Ângulo de venda: ";
        private const string SegundaOpcao = "Segunda opção: ";
        private const string MotivoSegunda = "Motivo: ";

        private AppSession _session;
        private IProposalRecommendationService _recommendationService;
        private Transform _contentRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _recommendationService = ServiceRegistry.Instance.Get<IProposalRecommendationService>();
            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;
            if (project == null)
            {
                AppendText(_contentRoot, NenhumProjeto);
                return;
            }
            if (project.Proposals == null || project.Proposals.Count == 0)
            {
                AppendText(_contentRoot, NenhumaProposta);
                project.LastRecommendationSummary = null;
                return;
            }

            var rec = _recommendationService?.Recommend(project);
            if (rec == null || string.IsNullOrEmpty(rec.RecommendedProposalId))
            {
                AppendText(_contentRoot, "Não foi possível gerar a recomendação.");
                return;
            }

            project.LastRecommendationSummary = rec;

            var recName = ResolveProposalName(project, rec.RecommendedProposalId);
            AppendText(_contentRoot, PropostaRecomendada + recName);
            AppendText(_contentRoot, Confianca + rec.RecommendationConfidenceScore + "/100");

            if (!string.IsNullOrEmpty(rec.ExecutiveSummary))
                AppendText(_contentRoot, ResumoExecutivo + rec.ExecutiveSummary);

            if (rec.WhyItWins != null && rec.WhyItWins.Count > 0)
            {
                AppendText(_contentRoot, PorQueVence);
                foreach (var w in rec.WhyItWins)
                    AppendText(_contentRoot, "  • " + w);
            }

            if (rec.Tradeoffs != null && rec.Tradeoffs.Count > 0)
            {
                AppendText(_contentRoot, TradeoffsLabel + string.Join("; ", rec.Tradeoffs));
            }

            if (!string.IsNullOrEmpty(rec.BudgetPositioning))
                AppendText(_contentRoot, Orcamento + rec.BudgetPositioning);
            if (!string.IsNullOrEmpty(rec.ExperiencePositioning))
                AppendText(_contentRoot, Experiencia + rec.ExperiencePositioning);
            if (!string.IsNullOrEmpty(rec.OperationalPositioning))
                AppendText(_contentRoot, Operacional + rec.OperationalPositioning);
            if (!string.IsNullOrEmpty(rec.SuggestedSalesAngle))
                AppendText(_contentRoot, AnguloVenda + rec.SuggestedSalesAngle);

            if (!string.IsNullOrEmpty(rec.SecondaryOptionId))
            {
                var secondName = ResolveProposalName(project, rec.SecondaryOptionId);
                AppendText(_contentRoot, SegundaOpcao + secondName);
                if (!string.IsNullOrEmpty(rec.SecondaryOptionReason))
                    AppendText(_contentRoot, MotivoSegunda + rec.SecondaryOptionReason);
            }
        }

        private static string ResolveProposalName(EventProject project, string proposalId)
        {
            if (string.IsNullOrEmpty(proposalId) || project?.Proposals == null) return "—";
            var p = project.Proposals.FirstOrDefault(x => x.Id == proposalId);
            return p?.Name ?? proposalId;
        }

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