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 plano de recuperação do ciclo: estratégia sugerida, ação principal, ações imediatas, impacto, esforço, responsável.
    /// </summary>
    public class EventCycleRecoveryPlanPanel : 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 plans = EventCycleRecoveryPlanController.GenerateRecoveryPlans(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 = "Plano de recuperação do ciclo e estratégia sugerida";
            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, 90, Refresh);
            CreateSmallButton(btnRow.transform, "Limpar concluídas", font, 120, () => { EventCycleRecoveryPlanController.ClearAllCompleted(); Refresh(); });

            if (plans == null || plans.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 ou nenhum plano gerado.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var plan in plans)
            {
                var block = new GameObject("Recovery_" + plan.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 {plan.CycleId} | Recuperação necessária: {(plan.IsRecoveryNeeded ? "Sim" : "Não")} | Confiança: {plan.RecoveryConfidenceLabel} | Gerado: {(plan.LastGeneratedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                AddBlock(block.transform, font, "Resumo da estratégia", plan.RecoverySummary);

                if (plan.PrimaryRecoveryAction != null)
                {
                    var p = plan.PrimaryRecoveryAction;
                    var topRow = new GameObject("Primary");
                    topRow.transform.SetParent(block.transform, false);
                    var topText = topRow.AddComponent<Text>();
                    topText.font = font;
                    topText.fontSize = 12;
                    topText.fontStyle = FontStyle.Bold;
                    topText.text = $"★ Principal: {p.Title} | Impacto {p.EstimatedRecoveryImpact} | Esforço {p.EstimatedRecoveryEffort} | Responsável {p.ResponsibleRole}";
                    topText.color = new Color(0.5f, 0.2f, 0.2f);
                    topRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                }

                if (plan.RecoveryActions != null)
                {
                    foreach (var a in plan.RecoveryActions)
                    {
                        var row = new GameObject("Action_" + a.RecoveryActionId);
                        row.transform.SetParent(block.transform, false);
                        var vLayout = row.AddComponent<VerticalLayoutGroup>();
                        vLayout.spacing = 2;
                        vLayout.childForceExpandHeight = false;
                        var line1 = new GameObject("Line1");
                        line1.transform.SetParent(row.transform, false);
                        var t1 = line1.AddComponent<Text>();
                        t1.font = font;
                        t1.fontSize = 11;
                        var immTag = a.IsImmediateAction ? " [IMEDIATA]" : "";
                        t1.text = $"[{a.Priority}] {a.Title}{immTag} — {a.Summary}";
                        if (a.Priority == EventCycleRecoveryPriority.Urgent) t1.color = new Color(0.75f, 0.2f, 0.2f);
                        else if (a.Priority == EventCycleRecoveryPriority.High) t1.color = new Color(0.6f, 0.3f, 0.2f);
                        line1.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                        var line2 = new GameObject("Line2");
                        line2.transform.SetParent(row.transform, false);
                        var t2 = line2.AddComponent<Text>();
                        t2.font = font;
                        t2.fontSize = 10;
                        t2.text = $"Impacto {a.EstimatedRecoveryImpact} | Esforço {a.EstimatedRecoveryEffort} | {a.ResponsibleRole} | Secção: {a.RelatedSectionKey ?? "—"}";
                        line2.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);
                        if (!string.IsNullOrEmpty(a.Notes))
                        {
                            var line3 = new GameObject("Line3");
                            line3.transform.SetParent(row.transform, false);
                            var t3 = line3.AddComponent<Text>();
                            t3.font = font;
                            t3.fontSize = 9;
                            t3.text = "Notas: " + a.Notes;
                            line3.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);
                        }
                        var btnRow2 = new GameObject("BtnMarkCompleted");
                        btnRow2.transform.SetParent(row.transform, false);
                        CreateSmallButton(btnRow2.transform, "Marcar concluída", font, 120, () => { EventCycleRecoveryPlanController.MarkRecoveryActionCompleted(a.RecoveryActionId); Refresh(); });
                        btnRow2.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
                        row.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 52);
                    }
                }
            }
        }

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