using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;
using EventsAppQuest.Web.Domain;
using EventsAppQuest.Web.Producer.Application;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Faixa de resumo do plano de ações: total, ação prioritária, bloqueantes, última geração.
    /// </summary>
    public class EventCycleActionPlanStripView : 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);

            EventCycleActionPlanController.GetTotals(plans, out var totalActions, out var blockingActions, out var topPriority, out var lastGenerated);

            var go = new GameObject("ActionPlanStrip");
            go.transform.SetParent(_content, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var text = go.AddComponent<Text>();
            text.font = font;
            text.fontSize = 12;
            var topLabel = topPriority != null ? topPriority.Title : "—";
            text.text = $"Ações: {totalActions} | Bloqueantes: {blockingActions} | Próxima: {topLabel} | Gerado: {(lastGenerated?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
            if (blockingActions > 0 || (topPriority != null && topPriority.Priority == EventsAppQuest.Web.Core.EventCycleActionPriority.Critical))
                text.color = new Color(0.2f, 0.5f, 0.2f);
        }

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