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 de ações recomendadas do ciclo: lista, destaque da prioritária, prioridade, responsável, motivo; marcar concluída (mock), limpar concluídas.
    /// </summary>
    public class EventCycleActionPlanPanel : 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 = EventCycleActionPlanController.GenerateActionPlans(orders, opportunities, proposals, sessions, followUps);

            var label = new GameObject("Label");
            label.transform.SetParent(_content, false);
            label.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var labelText = label.AddComponent<Text>();
            labelText.text = "Próximos passos recomendados (comercial e operação)";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            var btnRow = new GameObject("BtnRow");
            btnRow.transform.SetParent(_content, false);
            btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 26);
            var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
            hLayout.spacing = 6;
            hLayout.childForceExpandWidth = false;
            CreateSmallButton(btnRow.transform, "Atualizar", font, 70, Refresh);
            CreateSmallButton(btnRow.transform, "Limpar concluídas", font, 110, () => { EventCycleActionPlanController.ClearAllCompleted(); Refresh(); });

            var totalActions = 0;
            foreach (var p in plans)
                totalActions += p.TotalActions;

            if (totalActions == 0)
            {
                var empty = new GameObject("Empty");
                empty.transform.SetParent(_content, false);
                var emptyText = empty.AddComponent<Text>();
                emptyText.font = font;
                emptyText.fontSize = 11;
                emptyText.text = "Nenhuma ação pendente ou ciclos sem pedidos.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var plan in plans)
            {
                if (plan.Actions == null || plan.Actions.Count == 0) continue;
                var block = new GameObject("Plan_" + plan.CycleId);
                block.transform.SetParent(_content, false);
                var layout = block.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 2;
                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 = 12;
                headerText.fontStyle = FontStyle.Bold;
                headerText.text = $"{plan.CycleId} — {plan.TotalActions} ação(ões) | Bloqueantes: {plan.BlockingActions}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                if (plan.TopPriorityAction != null)
                {
                    var topRow = new GameObject("TopAction");
                    topRow.transform.SetParent(block.transform, false);
                    var topText = topRow.AddComponent<Text>();
                    topText.font = font;
                    topText.fontSize = 11;
                    topText.fontStyle = FontStyle.Bold;
                    topText.text = $"★ Próxima: [{plan.TopPriorityAction.Priority}] {plan.TopPriorityAction.Title} — {plan.TopPriorityAction.ResponsibleRole}";
                    topText.color = plan.TopPriorityAction.Priority == EventCycleActionPriority.Critical ? new Color(0.8f, 0.1f, 0.1f) : new Color(0.2f, 0.4f, 0.7f);
                    topRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                }

                foreach (var action in plan.Actions)
                {
                    var row = new GameObject("Action_" + action.ActionId);
                    row.transform.SetParent(block.transform, false);
                    var rowText = row.AddComponent<Text>();
                    rowText.font = font;
                    rowText.fontSize = 10;
                    rowText.text = $"[{action.Priority}] [{action.ResponsibleRole}] {action.Title} — {action.SuggestedReason}";
                    if (action.IsBlockingResolution) rowText.text = "⚠ " + rowText.text;
                    rowText.color = action.Priority == EventCycleActionPriority.Critical ? new Color(0.75f, 0.2f, 0.2f) : (action.Priority == EventCycleActionPriority.High ? new Color(0.6f, 0.4f, 0f) : Color.black);

                    var reasonRow = new GameObject("Reason_" + action.ActionId);
                    reasonRow.transform.SetParent(block.transform, false);
                    var reasonText = reasonRow.AddComponent<Text>();
                    reasonText.font = font;
                    reasonText.fontSize = 9;
                    reasonText.text = "Secção: " + (action.RelatedSectionKey ?? "—");
                    reasonRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);

                    var completeBtn = new GameObject("Complete_" + action.ActionId);
                    completeBtn.transform.SetParent(block.transform, false);
                    var compLe = completeBtn.AddComponent<LayoutElement>();
                    compLe.preferredHeight = 20;
                    compLe.preferredWidth = 110;
                    var compImg = completeBtn.AddComponent<Image>();
                    compImg.color = new Color(0.5f, 0.75f, 0.5f);
                    var compBtn = completeBtn.AddComponent<Button>();
                    compBtn.targetGraphic = compImg;
                    var aid = action.ActionId;
                    compBtn.onClick.AddListener(() => { EventCycleActionPlanController.MarkActionCompleted(aid); Refresh(); });
                    var compTextGo = new GameObject("Text");
                    compTextGo.transform.SetParent(completeBtn.transform, false);
                    var compTextRt = compTextGo.AddComponent<RectTransform>();
                    compTextRt.anchorMin = Vector2.zero;
                    compTextRt.anchorMax = Vector2.one;
                    compTextRt.offsetMin = Vector2.zero;
                    compTextRt.offsetMax = Vector2.zero;
                    var compText = compTextGo.AddComponent<Text>();
                    compText.text = "Marcar concluída";
                    compText.font = font;
                    compText.fontSize = 9;
                    compText.alignment = TextAnchor.MiddleCenter;
                }
            }
        }

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