using System.Linq;
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>
    /// Faixa de gargalos: prioritário, severidade, quantidade bloqueante, timestamp.
    /// </summary>
    public class EventCycleBottleneckStripView : 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 states = EventCycleBottleneckController.EvaluateBottlenecks(orders, opportunities, proposals, sessions, followUps);

            var first = states?.FirstOrDefault();
            if (first == null || (first.Bottlenecks == null || first.Bottlenecks.Count == 0))
            {
                var go = new GameObject("Strip");
                go.transform.SetParent(_content, false);
                go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
                var text = go.AddComponent<Text>();
                text.font = font;
                text.fontSize = 12;
                text.text = "Gargalos: nenhum ativo.";
                return;
            }

            var top = first.TopPriorityBottleneck;
            var topTitle = top != null ? top.Title : "—";
            var severityStr = top != null ? top.Severity.ToString() : "—";
            var blockCount = first.BlockingBottlenecks?.Count ?? 0;

            var go2 = new GameObject("Strip");
            go2.transform.SetParent(_content, false);
            go2.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var text2 = go2.AddComponent<Text>();
            text2.font = font;
            text2.fontSize = 12;
            text2.text = $"Gargalos: Prioritário {topTitle} [{severityStr}] | {blockCount} bloqueante(s) | {(first.LastEvaluatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
            if (top != null && (top.Severity == EventCycleBottleneckSeverity.Critical || top.Severity == EventCycleBottleneckSeverity.High))
                text2.color = new Color(0.7f, 0.2f, 0.2f);
        }

        private static void ClearContent(Transform content)
        {
            for (var i = content.childCount - 1; i >= 0; i--)
                Destroy(content.GetChild(i).gameObject);
        }
    }
}
