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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel do mapa de dependências do ciclo: nós, relações causa→efeito, dependências bloqueantes e resumo.
    /// </summary>
    public class EventCycleDependencyMapPanel : 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 maps = EventCycleDependencyMapController.BuildMaps(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 = "Mapa de dependências do ciclo (causa → efeito: comercial, Quest, operação)";
            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, "Recalcular", font, 80, Refresh);

            if (maps == null || maps.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 para mapa de dependências.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var map in maps)
            {
                var block = new GameObject("Map_" + map.CycleId);
                block.transform.SetParent(_content, false);
                var layout = block.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 4;
                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 = 14;
                headerText.fontStyle = FontStyle.Bold;
                headerText.text = $"Ciclo {map.CycleId} | {map.Nodes?.Count ?? 0} nós | {map.Links?.Count ?? 0} ligações | Avaliado: {(map.LastEvaluatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                AddBlock(block.transform, font, "Resumo", map.DependencySummary);

                if (map.MostCriticalDependency != null)
                {
                    var critRow = new GameObject("MostCritical");
                    critRow.transform.SetParent(block.transform, false);
                    var critText = critRow.AddComponent<Text>();
                    critText.font = font;
                    critText.fontSize = 11;
                    critText.text = $"Dependência mais crítica: {map.MostCriticalDependency.FromNodeId} → {map.MostCriticalDependency.ToNodeId} ({map.MostCriticalDependency.ImpactSummary})";
                    critText.color = new Color(0.65f, 0.2f, 0.2f);
                    critRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                }

                if (map.BlockingNodes != null && map.BlockingNodes.Count > 0)
                {
                    var blockLabel = new GameObject("BlockingLabel");
                    blockLabel.transform.SetParent(block.transform, false);
                    var blockLabelText = blockLabel.AddComponent<Text>();
                    blockLabelText.font = font;
                    blockLabelText.fontSize = 10;
                    blockLabelText.fontStyle = FontStyle.Bold;
                    blockLabelText.text = "Nós bloqueantes: " + string.Join(", ", map.BlockingNodes.ConvertAll(n => n.Title));
                    blockLabelText.color = new Color(0.6f, 0.2f, 0.2f);
                    blockLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }

                if (map.Nodes != null)
                {
                    var nodesLabel = new GameObject("NodesLabel");
                    nodesLabel.transform.SetParent(block.transform, false);
                    var nodesLabelText = nodesLabel.AddComponent<Text>();
                    nodesLabelText.font = font;
                    nodesLabelText.fontSize = 10;
                    nodesLabelText.fontStyle = FontStyle.Bold;
                    nodesLabelText.text = "Nós:";
                    nodesLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    foreach (var n in map.Nodes)
                    {
                        var row = new GameObject("Node_" + n.NodeId);
                        row.transform.SetParent(block.transform, false);
                        var rowText = row.AddComponent<Text>();
                        rowText.font = font;
                        rowText.fontSize = 10;
                        rowText.text = $"  [{n.Category}] {n.Title} — {n.StatusLabel}" + (n.IsBlockingOthers ? " ⚠ bloqueia" : "");
                        if (n.IsBlockingOthers) rowText.color = new Color(0.6f, 0.2f, 0.2f);
                        row.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }
                }

                if (map.Links != null && map.Links.Count > 0)
                {
                    var linksLabel = new GameObject("LinksLabel");
                    linksLabel.transform.SetParent(block.transform, false);
                    var linksLabelText = linksLabel.AddComponent<Text>();
                    linksLabelText.font = font;
                    linksLabelText.fontSize = 10;
                    linksLabelText.fontStyle = FontStyle.Bold;
                    linksLabelText.text = "Relações:";
                    linksLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    foreach (var l in map.Links)
                    {
                        var row = new GameObject("Link_" + l.FromNodeId);
                        row.transform.SetParent(block.transform, false);
                        var rowText = row.AddComponent<Text>();
                        rowText.font = font;
                        rowText.fontSize = 10;
                        rowText.text = $"  {l.FromNodeId} → {l.ToNodeId} [{l.DependencyType}]" + (l.IsCurrentlyBlocked ? " ⚠ bloqueado" : "");
                        if (l.IsCurrentlyBlocked) rowText.color = new Color(0.6f, 0.2f, 0.2f);
                        row.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }
                }
            }
        }

        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 void CreateSmallButton(Transform parent, string text, Font font, float width, System.Action onClick)
        {
            var go = new GameObject("Btn_" + text);
            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 = text;
            t.font = font;
            t.fontSize = 9;
            t.alignment = TextAnchor.MiddleCenter;
        }

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