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: status resumido do checklist, pronto para preparação, preparação confirmada, pendências principais.
    /// </summary>
    public class OrderChecklistPanel : 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 = "Checklist operacional (resumo)";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var orderId = order.OrderId;
                var state = ProducerPreparationChecklistController.EnsureChecklist(orderId);
                var readiness = ProducerExecutionReadinessController.Evaluate(orderId);

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

                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} | {ChecklistIndicatorHelper.GetChecklistSummaryLabel(state)} | {(readiness != null && readiness.IsReadyForPreparation ? "Pronto para preparação" : "Não pronto")} | {(state != null && state.IsPreparationConfirmed ? "Preparação confirmada" : "")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                if (state != null && !state.IsPreparationConfirmed && state.RequiredItems > state.CompletedRequiredItems)
                {
                    var pendRow = new GameObject("Pendencies");
                    pendRow.transform.SetParent(block.transform, false);
                    var pendText = pendRow.AddComponent<Text>();
                    pendText.font = font;
                    pendText.fontSize = 10;
                    pendText.text = "Pendências principais: " + string.Join(", ", state.Items.Where(i => i.IsRequired && !i.IsCompleted).Select(i => i.Title));
                    pendRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                }
            }
        }

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