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 visão resumida da carteira: cards por grupo, contagens, resumo geral, item mais importante por grupo.
    /// </summary>
    public class EventCyclePortfolioOverviewPanel : 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 overview = EventCyclePortfolioOverviewController.BuildOverview(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 = "Visão resumida da carteira (por status, risco e prioridade)";
            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, 90, Refresh);

            if (overview == null || overview.TotalCycles == 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 geral", overview.OverviewSummary);
            AddBlock(_content, font, "Total de ciclos", overview.TotalCycles.ToString());
            AddBlock(_content, font, "Última atualização", overview.LastUpdatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            if (overview.Groups != null)
            {
                foreach (var g in overview.Groups)
                {
                    var card = new GameObject("Group_" + g.GroupKey);
                    card.transform.SetParent(_content, false);
                    var layout = card.AddComponent<VerticalLayoutGroup>();
                    layout.spacing = 2;
                    layout.childForceExpandHeight = false;
                    layout.childForceExpandWidth = true;

                    var header = new GameObject("Header");
                    header.transform.SetParent(card.transform, false);
                    var headerText = header.AddComponent<Text>();
                    headerText.font = font;
                    headerText.fontSize = 12;
                    headerText.fontStyle = FontStyle.Bold;
                    headerText.text = $"[{g.Title}] {g.ItemCount} item(ns)";
                    if (g.GroupKey == EventCyclePortfolioOverviewController.GroupBlocked || g.GroupKey == EventCyclePortfolioOverviewController.GroupAtRisk)
                        headerText.color = new Color(0.7f, 0.2f, 0.2f);
                    header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                    var sumRow = new GameObject("Summary");
                    sumRow.transform.SetParent(card.transform, false);
                    var sumText = sumRow.AddComponent<Text>();
                    sumText.font = font;
                    sumText.fontSize = 10;
                    sumText.text = g.Summary ?? "—";
                    sumRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                    if (!string.IsNullOrEmpty(g.HighestPriorityItemId) && !string.IsNullOrEmpty(g.Notes))
                    {
                        var topRow = new GameObject("TopItem");
                        topRow.transform.SetParent(card.transform, false);
                        var topText = topRow.AddComponent<Text>();
                        topText.font = font;
                        topText.fontSize = 9;
                        topText.text = g.Notes;
                        topRow.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);
        }
    }
}
