using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;
using EventsAppQuest.Web.Domain;
using EventsAppQuest.Web.Producer.Application;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel de comparação entre snapshots: direção, melhorias/regressões e mudanças de prioridade/risco/gargalo/ação.
    /// </summary>
    public class EventCycleSnapshotComparisonPanel : MonoBehaviour, IWebContentRoot
    {
        private Transform _content;

        public void SetContentRoot(Transform contentRoot) => _content = contentRoot;

        private void Start()
        {
            Refresh();
            WebRuntimeContext.OnDataChanged += Refresh;
        }

        private void OnDestroy() => WebRuntimeContext.OnDataChanged -= Refresh;

        public void Refresh()
        {
            if (_content == null) return;
            ClearContent(_content);
            var data = WebRuntimeContext.DataService;
            if (data == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

            var orders = HandoffStore.GetOrders();
            var opportunities = data.GetOpportunities();
            var proposals = data.GetProposals();
            var sessions = data.GetSessions();
            var followUps = data.GetFollowUpTasks();
            var portfolioState = EventCyclePortfolioPriorityController.BuildPortfolioPriority(orders, opportunities, proposals, sessions, followUps);

            var titleRow = new GameObject("TitleRow");
            titleRow.transform.SetParent(_content, false);
            titleRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 26);
            var titleText = titleRow.AddComponent<Text>();
            titleText.text = "Comparação entre snapshots executivos (evolução do caso)";
            titleText.font = font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            var btnRow = new GameObject("BtnRow");
            btnRow.transform.SetParent(_content, false);
            btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
            hLayout.spacing = 6;
            hLayout.childForceExpandWidth = false;
            CreateSmallButton(btnRow.transform, "Comparar últimos (todos)", font, 170, () => { EventCycleSnapshotComparisonController.CompareLatestTwoForAllCycles(); Refresh(); });
            CreateSmallButton(btnRow.transform, "Limpar comparações", font, 130, () => { EventCycleSnapshotComparisonController.ClearAll(); Refresh(); });

            var global = EventCycleSnapshotComparisonController.GetGlobalComparisonState();
            AddBlock(_content, font, "Resumo", global.EvolutionSummary ?? "—");
            AddBlock(_content, font, "Total comparações", global.TotalComparisons.ToString());
            AddBlock(_content, font, "Última comparação", global.LastComparedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            if (portfolioState?.Items == null || portfolioState.Items.Count == 0)
            {
                var empty = new GameObject("Empty");
                empty.transform.SetParent(_content, false);
                var emptyText = empty.AddComponent<Text>();
                emptyText.font = font;
                emptyText.fontSize = 11;
                emptyText.text = "Nenhum ciclo na carteira. Gere pedidos a partir de oportunidades.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var item in portfolioState.Items)
            {
                var cycleId = item.CycleId;
                var snaps = ExecutiveSnapshotsStore.GetSnapshots(cycleId);
                var compState = EventCycleSnapshotComparisonController.GetComparisonState(cycleId);

                var block = new GameObject("Cycle_" + cycleId);
                block.transform.SetParent(_content, false);
                var layout = block.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 3;
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;

                var header = new GameObject("Header");
                header.transform.SetParent(block.transform, false);
                var headerText = header.AddComponent<Text>();
                headerText.font = font;
                headerText.fontSize = 12;
                headerText.fontStyle = FontStyle.Bold;
                headerText.text = $"{item.Title} [{cycleId}] | snapshots: {snaps.Count} | comparações: {compState.TotalComparisons}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                var btnRow2 = new GameObject("BtnRow");
                btnRow2.transform.SetParent(block.transform, false);
                var h2 = btnRow2.AddComponent<HorizontalLayoutGroup>();
                h2.spacing = 6;
                h2.childForceExpandWidth = false;
                CreateSmallButton(btnRow2.transform, "Comparar últimos", font, 120, () => { EventCycleSnapshotComparisonController.CompareLatestTwo(cycleId); Refresh(); });
                CreateSmallButton(btnRow2.transform, "Limpar ciclo", font, 90, () => { EventCycleSnapshotComparisonController.ClearCycle(cycleId); Refresh(); });
                btnRow2.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);

                if (compState.LatestComparison != null)
                {
                    var c = compState.LatestComparison;
                    AddBlock(block.transform, font, "Direção", c.OverallDirection.ToString());
                    AddBlock(block.transform, font, "Principal melhoria", c.MainImprovement ?? "—");
                    AddBlock(block.transform, font, "Principal regressão", c.MainRegression ?? "—");
                    AddBlock(block.transform, font, "Mudanças", c.ComparisonSummary ?? "—");
                    AddBlock(block.transform, font, "Timestamp", c.ComparedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");
                }
                else
                {
                    AddBlock(block.transform, font, "Estado", snaps.Count < 2 ? "Precisa de pelo menos 2 snapshots para comparar." : "Sem comparação ainda (clique em Comparar últimos).");
                }

                // Mostrar snapshot base vs comparado (últimos 2)
                if (snaps.Count >= 2)
                {
                    var compared = snaps[0];
                    var baseSnap = snaps[1];
                    AddBlock(block.transform, font, "Snapshot base", $"{baseSnap.CapturedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—"} | {baseSnap.ClosureStatus ?? "—"} | risco {baseSnap.RiskLabel ?? "—"} | prioridade {baseSnap.PriorityScore} | gargalo {baseSnap.MainBottleneck ?? "—"}");
                    AddBlock(block.transform, font, "Snapshot comparado", $"{compared.CapturedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—"} | {compared.ClosureStatus ?? "—"} | risco {compared.RiskLabel ?? "—"} | prioridade {compared.PriorityScore} | gargalo {compared.MainBottleneck ?? "—"}");
                }
            }
        }

        private static void AddBlock(Transform parent, Font font, string title, string content)
        {
            var go = new GameObject("Block_" + title);
            go.transform.SetParent(parent, false);
            var text = go.AddComponent<Text>();
            text.font = font;
            text.fontSize = 10;
            text.text = title + ": " + (content ?? "—");
            go.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
        }

        private static GameObject CreateSmallButton(Transform parent, string label, Font font, float width, System.Action onClick)
        {
            var go = new GameObject("Btn_" + label);
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(width, 22);
            var le = go.AddComponent<LayoutElement>();
            le.preferredWidth = width;
            le.preferredHeight = 22;
            var img = go.AddComponent<Image>();
            img.color = new Color(0.4f, 0.7f, 0.5f);
            var btn = go.AddComponent<Button>();
            btn.targetGraphic = img;
            btn.onClick.AddListener(() => onClick?.Invoke());
            var tGo = new GameObject("Text");
            tGo.transform.SetParent(go.transform, false);
            var tRt = tGo.AddComponent<RectTransform>();
            tRt.anchorMin = Vector2.zero;
            tRt.anchorMax = Vector2.one;
            tRt.offsetMin = Vector2.zero;
            tRt.offsetMax = Vector2.zero;
            var t = tGo.AddComponent<Text>();
            t.text = label;
            t.font = font;
            t.fontSize = 9;
            t.alignment = TextAnchor.MiddleCenter;
            return go;
        }

        private static void ClearContent(Transform content)
        {
            for (var i = content.childCount - 1; i >= 0; i--)
                Destroy(content.GetChild(i).gameObject);
        }
    }
}

