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

namespace EventsAppQuest.Web.Producer.Presentation
{
    /// <summary>
    /// Vista de status dos pedidos e atualizações de status.
    /// </summary>
    public class ProducerStatusView : MonoBehaviour, IProducerContentRoot
    {
        private Transform _content;

        public void SetContentRoot(Transform contentRoot) => _content = contentRoot;

        private void Start() => Refresh();

        public void Refresh()
        {
            if (_content == null) return;
            ClearContent(_content);
            var service = ProducerRuntimeContext.DataService;
            if (service == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            foreach (var order in service.GetOrders())
            {
                var go = new GameObject("StatusRow");
                go.transform.SetParent(_content, false);
                var rt = go.AddComponent<RectTransform>();
                rt.sizeDelta = new Vector2(0, 20);
                var text = go.AddComponent<Text>();
                text.text = $"{order.OrderId}: {order.ProducerOrderStatus} | Prioridade: {order.FollowUpPriority}";
                text.font = font;
                text.fontSize = 11;
            }
            foreach (var upd in service.GetStatusUpdates())
            {
                var go2 = new GameObject("UpdateRow");
                go2.transform.SetParent(_content, false);
                var rt2 = go2.AddComponent<RectTransform>();
                rt2.sizeDelta = new Vector2(0, 18);
                var text2 = go2.AddComponent<Text>();
                text2.text = $"  → {upd.OrderId}: {upd.PreviousStatus} → {upd.NewStatus} ({upd.CreatedAt:g})";
                text2.font = font;
                text2.fontSize = 10;
            }
        }

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