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 dashboard do ciclo: número de ciclos, secções saudáveis/pendentes, última atualização.
    /// </summary>
    public class EventCycleDashboardStripView : 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 states = EventCycleDashboardController.BuildDashboard(orders, opportunities, proposals, sessions);

            var totalHealthy = 0;
            var totalPending = 0;
            var lastUpdated = default(System.DateTime?);
            foreach (var state in states)
            {
                EventCycleDashboardController.CountSectionsHealth(state, out var h, out var p);
                totalHealthy += h;
                totalPending += p;
                if (state.LastUpdatedAt.HasValue && (!lastUpdated.HasValue || state.LastUpdatedAt.Value > lastUpdated.Value))
                    lastUpdated = state.LastUpdatedAt;
            }

            var go = new GameObject("CycleStrip");
            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 = $"Ciclos: {states.Count} | Secções saudáveis: {totalHealthy} | Pendentes: {totalPending} | Última atualização: {(lastUpdated?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
        }

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