using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Producer.Application;
using EventsAppQuest.Web.Producer.Domain;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel no CRM do hotel: readiness do pedido, bloqueios pendentes, resumo operacional, pronto para preparação / não pronto.
    /// </summary>
    public class OrderReadinessPanel : 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 font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

            var label = new GameObject("Label");
            label.transform.SetParent(_content, false);
            var labelRt = label.AddComponent<RectTransform>();
            labelRt.sizeDelta = new Vector2(0, 22);
            var labelText = label.AddComponent<Text>();
            labelText.text = "Prontidão para preparação / execução";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var orderId = order.OrderId;
                var state = ProducerExecutionReadinessController.Evaluate(orderId);
                if (state == null) continue;

                var block = new GameObject("Readiness_" + orderId);
                block.transform.SetParent(_content, false);
                var layout = block.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 4;
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;

                var statusLabel = ReadinessIndicatorHelper.GetReadinessLabel(state);
                var header = new GameObject("Header");
                header.transform.SetParent(block.transform, false);
                var headerText = header.AddComponent<Text>();
                headerText.font = font;
                headerText.fontSize = 12;
                headerText.text = $"{orderId} | {statusLabel} | {(state.IsReadyForPreparation ? "Pronto para preparação" : "Não pronto")} | Revisão vigente: {state.ActiveScopeRevisionId ?? "—"}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                var summaryRow = new GameObject("Summary");
                summaryRow.transform.SetParent(block.transform, false);
                var summaryText = summaryRow.AddComponent<Text>();
                summaryText.font = font;
                summaryText.fontSize = 10;
                summaryText.text = "Resumo: " + (state.ReadinessSummary ?? "—");
                summaryRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                var blockingRow = new GameObject("Blocking");
                blockingRow.transform.SetParent(block.transform, false);
                var blockingText = blockingRow.AddComponent<Text>();
                blockingText.font = font;
                blockingText.fontSize = 10;
                var unresolved = state.BlockingItems.Where(b => !b.IsResolved).ToList();
                blockingText.text = unresolved.Count == 0 ? "Sem bloqueios pendentes." : "Bloqueios: " + string.Join("; ", unresolved.Select(b => b.Title + " (" + b.Severity + ")"));
                blockingRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, unresolved.Count > 0 ? 16 + unresolved.Count * 12 : 16);
            }
        }

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