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 alertas e pendências críticas do ciclo: lista, destaque de críticos, marcar como resolvido (mock), limpar resolvidos.
    /// </summary>
    public class EventCycleAlertsPanel : 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 alertStates = EventCycleAlertController.EvaluateAllAlerts(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 = "Alertas e pendências críticas do ciclo";
            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 resolvidos", font, 110, () => { EventCycleAlertController.ClearAllResolved(); Refresh(); });

            var totalAlerts = 0;
            foreach (var ast in alertStates)
                totalAlerts += ast.TotalAlerts;

            if (totalAlerts == 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 alerta activo. Os ciclos estão sem pendências críticas ou foram marcados como resolvidos.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var ast in alertStates)
            {
                if (ast.Alerts == null || ast.Alerts.Count == 0) continue;
                var block = new GameObject("Alerts_" + ast.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 = $"{ast.CycleId} — {ast.TotalAlerts} alerta(s) | Bloqueantes: {ast.BlockingAlerts}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                foreach (var alert in ast.Alerts)
                {
                    var row = new GameObject("Alert_" + alert.AlertId);
                    row.transform.SetParent(block.transform, false);
                    var rowRt = row.AddComponent<RectTransform>();
                    rowRt.sizeDelta = new Vector2(0, 36);
                    var rowText = row.AddComponent<Text>();
                    rowText.font = font;
                    rowText.fontSize = 10;
                    rowText.text = $"[{alert.Severity}] [{alert.Category}] {alert.Title} — {alert.Summary}";
                    if (alert.IsBlocking) rowText.text = "⚠ " + rowText.text;
                    if (alert.Severity == EventCycleAlertSeverity.Critical) rowText.color = new Color(0.8f, 0.1f, 0.1f);
                    else if (alert.Severity == EventCycleAlertSeverity.High) rowText.color = new Color(0.7f, 0.4f, 0f);

                    var actionRow = new GameObject("Action_" + alert.AlertId);
                    actionRow.transform.SetParent(block.transform, false);
                    var actText = actionRow.AddComponent<Text>();
                    actText.font = font;
                    actText.fontSize = 9;
                    actText.text = "Ação sugerida: " + (alert.SuggestedAction ?? "—") + " | Secção: " + (alert.RelatedSectionKey ?? "—");
                    actionRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                    var resolveBtn = new GameObject("Resolve_" + alert.AlertId);
                    resolveBtn.transform.SetParent(block.transform, false);
                    var resLe = resolveBtn.AddComponent<LayoutElement>();
                    resLe.preferredHeight = 20;
                    resLe.preferredWidth = 100;
                    var resImg = resolveBtn.AddComponent<Image>();
                    resImg.color = new Color(0.5f, 0.75f, 0.5f);
                    var resBtn = resolveBtn.AddComponent<Button>();
                    resBtn.targetGraphic = resImg;
                    var aid = alert.AlertId;
                    resBtn.onClick.AddListener(() => { EventCycleAlertController.MarkAlertResolved(aid); Refresh(); });
                    var resTextGo = new GameObject("Text");
                    resTextGo.transform.SetParent(resolveBtn.transform, false);
                    var resTextRt = resTextGo.AddComponent<RectTransform>();
                    resTextRt.anchorMin = Vector2.zero;
                    resTextRt.anchorMax = Vector2.one;
                    resTextRt.offsetMin = Vector2.zero;
                    resTextRt.offsetMax = Vector2.zero;
                    var resText = resTextGo.AddComponent<Text>();
                    resText.text = "Marcar resolvido";
                    resText.font = font;
                    resText.fontSize = 9;
                    resText.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);
        }
    }
}
