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.Producer.Presentation
{
    /// <summary>
    /// Vista no painel do produtor: readiness do pedido, bloqueios, checklist do que falta, pronto para execução, marcar bloqueio como resolvido (mock).
    /// </summary>
    public class ProducerReadinessView : 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");

            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 execução";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in service.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.IsReadyForExecution ? "Pronto para execuçã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 checklistLabel = new GameObject("ChecklistLabel");
                checklistLabel.transform.SetParent(block.transform, false);
                var checklistLabelText = checklistLabel.AddComponent<Text>();
                checklistLabelText.font = font;
                checklistLabelText.fontSize = 11;
                checklistLabelText.text = "Checklist / Bloqueios:";
                checklistLabelText.fontStyle = FontStyle.Bold;
                checklistLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                foreach (var item in state.BlockingItems)
                {
                    var row = new GameObject("Block_" + item.Code);
                    row.transform.SetParent(block.transform, false);
                    var rowRt = row.AddComponent<RectTransform>();
                    rowRt.sizeDelta = new Vector2(0, 24);

                    var rowText = new GameObject("Text");
                    rowText.transform.SetParent(row.transform, false);
                    var rt = rowText.AddComponent<RectTransform>();
                    rt.anchorMin = new Vector2(0, 0);
                    rt.anchorMax = new Vector2(1, 1);
                    rt.offsetMin = new Vector2(0, 0);
                    rt.offsetMax = new Vector2(-90, 0);
                    var t = rowText.AddComponent<Text>();
                    t.font = font;
                    t.fontSize = 10;
                    t.text = (item.IsResolved ? "[Resolvido] " : "") + item.Title + " — " + item.Summary;

                    var resolveBtn = new GameObject("ResolveBtn");
                    resolveBtn.transform.SetParent(row.transform, false);
                    var btnRt = resolveBtn.AddComponent<RectTransform>();
                    btnRt.anchorMin = new Vector2(1, 0.5f);
                    btnRt.anchorMax = new Vector2(1, 0.5f);
                    btnRt.pivot = new Vector2(1, 0.5f);
                    btnRt.sizeDelta = new Vector2(82, 20);
                    btnRt.anchoredPosition = Vector2.zero;
                    var img = resolveBtn.AddComponent<Image>();
                    img.color = item.IsResolved ? new Color(0.6f, 0.6f, 0.6f) : new Color(0.4f, 0.7f, 0.5f);
                    var btn = resolveBtn.AddComponent<Button>();
                    btn.targetGraphic = img;
                    var code = item.Code;
                    btn.onClick.AddListener(() =>
                    {
                        if (item.IsResolved)
                            ProducerExecutionReadinessController.MarkBlockingUnresolved(orderId, code);
                        else
                            ProducerExecutionReadinessController.MarkBlockingResolved(orderId, code);
                        Refresh();
                    });
                    var btnTextGo = new GameObject("Text");
                    btnTextGo.transform.SetParent(resolveBtn.transform, false);
                    var btnTextRt = btnTextGo.AddComponent<RectTransform>();
                    btnTextRt.anchorMin = Vector2.zero;
                    btnTextRt.anchorMax = Vector2.one;
                    btnTextRt.offsetMin = Vector2.zero;
                    btnTextRt.offsetMax = Vector2.zero;
                    var btnText = btnTextGo.AddComponent<Text>();
                    btnText.text = item.IsResolved ? "Desfazer" : "Resolvido";
                    btnText.font = font;
                    btnText.fontSize = 9;
                    btnText.alignment = TextAnchor.MiddleCenter;
                }
            }
        }

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