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 revisão comercial da proposta e comparação com versões salvas.
    /// Usa referências explícitas a containers (sem Find por nome).
    /// </summary>
    public class ProposalReviewView : MonoBehaviour
    {
        private const string Title = "Revisão Comercial / Comparação de Propostas";
        private const string RevisarProposta = "Revisar proposta";
        private const string SalvarVersao = "Salvar versão atual";
        private const string NenhumProjeto = "Nenhum projeto iniciado.";
        private const string ProntoSim = "Sim";
        private const string ProntoNao = "Não";
        private const string Prontidao = "Pronto para apresentação: ";
        private const string PontosFortes = "Pontos fortes";
        private const string Alertas = "Alertas";
        private const string ElementosAusentes = "Elementos ausentes";
        private const string Comparacao = "Comparação (atual vs versões salvas)";
        private const string Atual = "Atual";
        private const string ValidText = "Válida";
        private const string WarningsText = "Avisos";
        private const string InvalidText = "Inválida";

        private AppSession _session;
        private IProposalPricingService _pricingService;
        private Transform _reviewRoot;
        private Transform _snapshotsRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _pricingService = ServiceRegistry.Instance.Get<IProposalPricingService>();
            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 btnRow = new GameObject("ButtonRow");
            btnRow.transform.SetParent(transform, false);
            var btnRowHlg = btnRow.AddComponent<HorizontalLayoutGroup>();
            btnRowHlg.spacing = 10;
            btnRowHlg.childForceExpandWidth = false;
            btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 30);
            CreateButton(btnRow.transform, RevisarProposta, () => _session?.ReviewProposal());
            CreateButton(btnRow.transform, SalvarVersao, () => _session?.SaveCurrentVersion());

            _reviewRoot = new GameObject("ReviewRoot").transform;
            _reviewRoot.SetParent(transform, false);
            _reviewRoot.gameObject.AddComponent<LayoutElement>().preferredHeight = 160;
            var reviewVlg = _reviewRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            reviewVlg.spacing = 4;
            reviewVlg.childForceExpandHeight = false;
            reviewVlg.childForceExpandWidth = true;

            var compLabel = new GameObject("CompareLabel");
            compLabel.transform.SetParent(transform, false);
            compLabel.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
            var compText = compLabel.AddComponent<Text>();
            compText.text = Comparacao;
            compText.font = _font;
            compText.fontSize = 13;
            compText.fontStyle = FontStyle.Bold;

            _snapshotsRoot = new GameObject("SnapshotsRoot").transform;
            _snapshotsRoot.SetParent(transform, false);
            _snapshotsRoot.gameObject.AddComponent<LayoutElement>().preferredHeight = 120;
            var snapVlg = _snapshotsRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            snapVlg.spacing = 4;
            snapVlg.childForceExpandHeight = false;
            snapVlg.childForceExpandWidth = true;
        }

        private void CreateButton(Transform parent, string label, System.Action onClick)
        {
            var go = new GameObject("Btn");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(140, 26);
            var le = go.AddComponent<LayoutElement>();
            le.preferredWidth = 140;
            le.preferredHeight = 26;
            var btn = go.AddComponent<Button>();
            go.AddComponent<Image>().color = new Color(0.4f, 0.55f, 0.7f, 1f);
            var textGo = new GameObject("Text");
            textGo.transform.SetParent(go.transform, false);
            var textRt = textGo.AddComponent<RectTransform>();
            textRt.anchorMin = Vector2.zero;
            textRt.anchorMax = Vector2.one;
            textRt.offsetMin = Vector2.zero;
            textRt.offsetMax = Vector2.zero;
            var text = textGo.AddComponent<Text>();
            text.text = label;
            text.font = _font;
            text.fontSize = 12;
            text.alignment = TextAnchor.MiddleCenter;
            text.color = Color.white;
            btn.onClick.AddListener(() => onClick?.Invoke());
        }

        private void UpdateContent()
        {
            ClearChildren(_reviewRoot);
            ClearChildren(_snapshotsRoot);

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

            var review = project.LastProposalReviewSummary;
            if (review != null)
            {
                AppendText(_reviewRoot, Prontidao + (review.IsReadyForPresentation ? ProntoSim : ProntoNao));
                AppendText(_reviewRoot, $"Validação: {ValidationStatusText(review.ValidationStatus)} | Orçamento: {review.BudgetLevel ?? "—"} | Tema: {review.ThemeName ?? "—"} | Etapas: {review.PresentationStepCount}");
                if (!string.IsNullOrEmpty(review.CapacitySummary))
                    AppendText(_reviewRoot, "Capacidade: " + review.CapacitySummary);
                if (!string.IsNullOrEmpty(review.FlowSummary))
                    AppendText(_reviewRoot, "Fluxo: " + review.FlowSummary);
                if (!string.IsNullOrEmpty(review.SetupTimelineSummary))
                    AppendText(_reviewRoot, "Cronograma: " + review.SetupTimelineSummary);
                if (!string.IsNullOrEmpty(review.SupplierCoverageSummary))
                    AppendText(_reviewRoot, "Cobertura fornecedores: " + review.SupplierCoverageSummary);
                if (!string.IsNullOrEmpty(review.CommercialReadingSummary))
                    AppendText(_reviewRoot, "Comercial: " + review.CommercialReadingSummary);
                if (!string.IsNullOrEmpty(review.JourneySummary))
                    AppendText(_reviewRoot, "Jornada: " + review.JourneySummary);
                if (!string.IsNullOrEmpty(review.TransitionSummary))
                    AppendText(_reviewRoot, "Transições: " + review.TransitionSummary + (review.TransitionCount > 0 ? " (" + review.TransitionCount + " trans., fluidez " + review.AverageSmoothnessScore + ")" : ""));
                if (!string.IsNullOrEmpty(review.GuidedTourSummary))
                    AppendText(_reviewRoot, "Roteiro guiado: " + review.GuidedTourSummary + (review.GuidedTourStepCount > 0 ? " (" + review.GuidedTourStepCount + " passos)" : "") + (review.ReadyForGuidedPresentation ? " — Pronta para apresentação guiada" : ""));
                if (!string.IsNullOrEmpty(review.VisualHotspotSummary))
                    AppendText(_reviewRoot, "Hotspots visuais: " + review.VisualHotspotSummary + (review.VisualHotspotCount > 0 && !string.IsNullOrEmpty(review.PrimaryHotspotTitle) ? " — Principal: " + review.PrimaryHotspotTitle : "") + (review.HasPremiumHotspots ? " | Destaques premium" : ""));
                if (!string.IsNullOrEmpty(review.SceneStateSummary))
                    AppendText(_reviewRoot, "Estados da cena: " + review.SceneStateSummary + (review.SceneStateCount > 0 ? " (" + review.SceneStateCount + " estados)" : "") + (review.HasStructuredVisualEvolution ? " — Evolução visual estruturada" : ""));
                AppendList(_reviewRoot, PontosFortes, review.Strengths, new Color(0.2f, 0.5f, 0.2f, 1f));
                AppendList(_reviewRoot, Alertas, review.Warnings, new Color(0.6f, 0.4f, 0.1f, 1f));
                AppendList(_reviewRoot, ElementosAusentes, review.MissingElements, new Color(0.5f, 0.3f, 0.3f, 1f));
            }
            else
                AppendText(_reviewRoot, "Clique em \"" + RevisarProposta + "\" para gerar a revisão.");

            var pricing = _pricingService?.GetPricingSummary(project);
            var currentValidation = project.LastCompositionValidation?.Status ?? CompositionValidationStatus.Valid;
            AppendComparisonRow(_snapshotsRoot, Atual, pricing?.TotalEstimated ?? 0f, project.ShowroomItemIds?.Count ?? 0, pricing?.SupplierCount ?? 0, currentValidation, true);

            foreach (var snap in _session?.SavedSnapshots ?? new List<ProposalVersionSnapshot>())
                AppendComparisonRow(_snapshotsRoot, snap.Name + " (" + snap.CreatedAt + ")", snap.TotalEstimatedPrice, snap.ShowroomItemCount, snap.SupplierCount, snap.ValidationStatus, false);
        }

        private static string ValidationStatusText(CompositionValidationStatus s)
        {
            switch (s)
            {
                case CompositionValidationStatus.Valid: return ValidText;
                case CompositionValidationStatus.HasWarnings: return WarningsText;
                case CompositionValidationStatus.Invalid: return InvalidText;
                default: return "—";
            }
        }

        private void AppendList(Transform parent, string title, List<string> items, Color color)
        {
            if (items == null || items.Count == 0) return;
            var line = new GameObject("Line");
            line.transform.SetParent(parent, false);
            line.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
            var t = line.AddComponent<Text>();
            t.text = title + ": " + string.Join("; ", items);
            t.font = _font;
            t.fontSize = 11;
            t.color = color;
        }

        private void AppendComparisonRow(Transform parent, string label, float total, int items, int suppliers, CompositionValidationStatus validation, bool isCurrent)
        {
            var row = new GameObject("Row");
            row.transform.SetParent(parent, false);
            row.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
            var t = row.AddComponent<Text>();
            t.text = $"{label} — R$ {total:N0} | {items} itens | {suppliers} forn. | {ValidationStatusText(validation)}";
            t.font = _font;
            t.fontSize = 11;
            t.fontStyle = isCurrent ? FontStyle.Bold : FontStyle.Normal;
        }

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