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 da fila gerencial de atenção: lista priorizada, caso prioritário, mais crítico, melhor recuperação, score e razão.
    /// </summary>
    public class EventCyclePortfolioPriorityPanel : 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 state = 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 = "Priorização executiva e fila gerencial de atençã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, "Gerar priorização", font, 130, Refresh);
            CreateSmallButton(btnRow.transform, "Recalcular", font, 90, Refresh);

            if (state?.Items == null || state.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;
            }

            AddBlock(_content, font, "Resumo", state.PrioritizationSummary);
            AddBlock(_content, font, "Prioritário", state.HighestPriorityItem != null ? $"{state.HighestPriorityItem.Title} (score {state.HighestPriorityItem.PriorityScore})" : "—");
            AddBlock(_content, font, "Mais crítico", state.HighestRiskItem != null ? state.HighestRiskItem.Title + " — " + state.HighestRiskItem.RiskLevelLabel : "—");
            AddBlock(_content, font, "Melhor recuperação", state.BestRecoveryOpportunity != null ? state.BestRecoveryOpportunity.Title + " — " + (state.BestRecoveryOpportunity.SimulatedBestScenarioDelta ?? "—") : "—");
            AddBlock(_content, font, "Mais perto de fechar", state.NearestToCloseItem != null ? state.NearestToCloseItem.Title : "—");
            AddBlock(_content, font, "Média score prioridade", state.AveragePriorityScore.ToString("F1"));
            AddBlock(_content, font, "Última priorização", state.LastPrioritizedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            var rank = 0;
            foreach (var item in state.Items)
            {
                rank++;
                var block = new GameObject("Item_" + item.CycleId);
                block.transform.SetParent(_content, false);
                var layout = block.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 2;
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;

                var isTop = state.HighestPriorityItem?.CycleId == item.CycleId;
                var header = new GameObject("Header");
                header.transform.SetParent(block.transform, false);
                var headerText = header.AddComponent<Text>();
                headerText.font = font;
                headerText.fontSize = isTop ? 13 : 11;
                headerText.fontStyle = isTop ? FontStyle.Bold : FontStyle.Normal;
                headerText.text = $"#{rank} [{item.PriorityScore}] {item.Title}";
                if (isTop) headerText.color = new Color(0.2f, 0.45f, 0.2f);
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                var line2 = new GameObject("Line2");
                line2.transform.SetParent(block.transform, false);
                var t2 = line2.AddComponent<Text>();
                t2.font = font;
                t2.fontSize = 10;
                t2.text = $"Risco: {item.RiskLevelLabel} | Gargalo: {item.BottleneckSeverityLabel} | Performance: {item.OverallCyclePerformanceScore}";
                line2.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                var line3 = new GameObject("Line3");
                line3.transform.SetParent(block.transform, false);
                var t3 = line3.AddComponent<Text>();
                t3.font = font;
                t3.fontSize = 9;
                t3.text = "Razão: " + (item.PriorityReason ?? "—");
                line3.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);

                var line4 = new GameObject("Line4");
                line4.transform.SetParent(block.transform, false);
                var t4 = line4.AddComponent<Text>();
                t4.font = font;
                t4.fontSize = 9;
                t4.text = $"Ação: {item.TopRecommendedAction} | Recuperação: {item.TopRecoveryAction} | Delta: {item.SimulatedBestScenarioDelta}";
                line4.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);
            }
        }

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