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 métricas consolidadas do ciclo: score geral, sub-indicadores, label, fatores positivos e negativos.
    /// </summary>
    public class EventCycleMetricsPanel : 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 metricsList = EventCycleMetricsController.CalculateMetrics(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 = "Métricas consolidadas do ciclo (performance comercial e operacional)";
            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 (metricsList == null || metricsList.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 com pedido. Gere um pedido para ver as métricas.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var m in metricsList)
            {
                var block = new GameObject("Metrics_" + m.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 {m.CycleId} | Score: {m.OverallCyclePerformanceScore} | {m.PerformanceLabel} | Calculado: {(m.LastCalculatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
                if (m.PerformanceLabel == "Excellent") headerText.color = new Color(0.2f, 0.5f, 0.2f);
                else if (m.PerformanceLabel == "Poor") headerText.color = new Color(0.75f, 0.2f, 0.2f);
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                var subRow = new GameObject("SubIndicators");
                subRow.transform.SetParent(block.transform, false);
                var subText = subRow.AddComponent<Text>();
                subText.font = font;
                subText.fontSize = 10;
                subText.text = $"Quest:{m.QuestCompletionSignalScore} Comercial:{m.CommercialConversionSignalScore} Handoff:{m.HandoffDelayRiskScore} Produtor:{m.ProducerResponseScore} Comms:{m.CommunicationActivityScore} Prep:{m.PreparationReadinessScore} Exec:{m.ExecutionProgressScore} Aceite:{m.FinalAcceptanceCompletionScore} | Revisões escopo:{m.ScopeRevisionCount}";
                subRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                if (m.TopPositiveFactors != null && m.TopPositiveFactors.Count > 0)
                {
                    var posLabel = new GameObject("PosLabel");
                    posLabel.transform.SetParent(block.transform, false);
                    var posLabelText = posLabel.AddComponent<Text>();
                    posLabelText.font = font;
                    posLabelText.fontSize = 10;
                    posLabelText.fontStyle = FontStyle.Bold;
                    posLabelText.text = "Fatores positivos: " + string.Join("; ", m.TopPositiveFactors);
                    posLabelText.color = new Color(0.2f, 0.5f, 0.2f);
                    posLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
                if (m.TopNegativeFactors != null && m.TopNegativeFactors.Count > 0)
                {
                    var negLabel = new GameObject("NegLabel");
                    negLabel.transform.SetParent(block.transform, false);
                    var negLabelText = negLabel.AddComponent<Text>();
                    negLabelText.font = font;
                    negLabelText.fontSize = 10;
                    negLabelText.fontStyle = FontStyle.Bold;
                    negLabelText.text = "Fatores negativos: " + string.Join("; ", m.TopNegativeFactors);
                    negLabelText.color = new Color(0.6f, 0.2f, 0.2f);
                    negLabel.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);
        }
    }
}
