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 do resumo executivo do ciclo: status geral, comercial, Quest, produtor, execução, aceite final, riscos, avanços, próxima ação.
    /// </summary>
    public class EventCycleExecutiveSummaryPanel : 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 summaries = EventCycleExecutiveSummaryController.GenerateSummaries(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 = "Resumo executivo do ciclo (visão gestã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, "Atualizar", font, 70, Refresh);

            if (summaries == null || summaries.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 o resumo executivo.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var s in summaries)
            {
                var block = new GameObject("Summary_" + s.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 = $"{s.ExecutiveTitle} | {s.OverallStatusLabel} | Gerado: {(s.GeneratedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                AddBlock(block.transform, font, "Comercial", s.CommercialSummary);
                AddBlock(block.transform, font, "Sessão Quest", s.QuestSessionSummary);
                AddBlock(block.transform, font, "Handoff", s.HandoffSummary);
                AddBlock(block.transform, font, "Produtor", s.ProducerSummary);
                AddBlock(block.transform, font, "Execução", s.ExecutionSummary);
                AddBlock(block.transform, font, "Aceite final", s.FinalAcceptanceSummary);

                if (s.TopRisks != null && s.TopRisks.Count > 0)
                {
                    var riskLabel = new GameObject("RisksLabel");
                    riskLabel.transform.SetParent(block.transform, false);
                    var riskLabelText = riskLabel.AddComponent<Text>();
                    riskLabelText.font = font;
                    riskLabelText.fontSize = 11;
                    riskLabelText.fontStyle = FontStyle.Bold;
                    riskLabelText.text = "Riscos principais:";
                    riskLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                    foreach (var r in s.TopRisks)
                    {
                        var row = new GameObject("Risk");
                        row.transform.SetParent(block.transform, false);
                        var rowText = row.AddComponent<Text>();
                        rowText.font = font;
                        rowText.fontSize = 10;
                        rowText.text = $"  • [{r.SeverityOrImportance}] {r.Title}: {r.Summary}";
                        row.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }
                }

                if (s.TopProgressPoints != null && s.TopProgressPoints.Count > 0)
                {
                    var progLabel = new GameObject("ProgressLabel");
                    progLabel.transform.SetParent(block.transform, false);
                    var progLabelText = progLabel.AddComponent<Text>();
                    progLabelText.font = font;
                    progLabelText.fontSize = 11;
                    progLabelText.fontStyle = FontStyle.Bold;
                    progLabelText.text = "Avanços principais:";
                    progLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                    foreach (var p in s.TopProgressPoints)
                    {
                        var row = new GameObject("Progress");
                        row.transform.SetParent(block.transform, false);
                        var rowText = row.AddComponent<Text>();
                        rowText.font = font;
                        rowText.fontSize = 10;
                        rowText.text = $"  • {p.Title} — {p.Summary}";
                        row.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }
                }

                if (s.TopRecommendedAction != null)
                {
                    var actionLabel = new GameObject("ActionLabel");
                    actionLabel.transform.SetParent(block.transform, false);
                    var actionLabelText = actionLabel.AddComponent<Text>();
                    actionLabelText.font = font;
                    actionLabelText.fontSize = 11;
                    actionLabelText.fontStyle = FontStyle.Bold;
                    actionLabelText.text = "Próxima ação principal:";
                    actionLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                    var actionRow = new GameObject("TopAction");
                    actionRow.transform.SetParent(block.transform, false);
                    var actionText = actionRow.AddComponent<Text>();
                    actionText.font = font;
                    actionText.fontSize = 10;
                    actionText.text = $"  ★ {s.TopRecommendedAction.Title} — {s.TopRecommendedAction.Summary} [{s.TopRecommendedAction.Notes}]";
                    actionRow.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);
        }
    }
}
