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: checklist operacional, marcar itens concluídos, progresso, confirmar preparação, pendências obrigatórias.
    /// </summary>
    public class ProducerPreparationChecklistView : 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 = "Checklist operacional e confirmação de preparação";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in service.GetOrders())
            {
                var orderId = order.OrderId;
                var state = ProducerPreparationChecklistController.EnsureChecklist(orderId);
                if (state == null) continue;

                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.GetChecklistLabel(state)} | {state.CompletedItems}/{state.TotalItems} itens | Obrigatórios: {state.CompletedRequiredItems}/{state.RequiredItems}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

                if (state.IsPreparationConfirmed)
                {
                    var confRow = new GameObject("Confirmed");
                    confRow.transform.SetParent(block.transform, false);
                    var confText = confRow.AddComponent<Text>();
                    confText.font = font;
                    confText.fontSize = 10;
                    confText.text = "Preparação confirmada em " + state.PreparationConfirmedAt?.ToString("g") + ". " + (state.PreparationSummary ?? "");
                    confRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                }
                else
                {
                    if (state.CompletedRequiredItems < state.RequiredItems)
                    {
                        var pendRow = new GameObject("Pendencies");
                        pendRow.transform.SetParent(block.transform, false);
                        var pendText = pendRow.AddComponent<Text>();
                        pendText.font = font;
                        pendText.fontSize = 10;
                        pendText.color = new Color(0.7f, 0.2f, 0.2f);
                        pendText.text = "Ainda há " + (state.RequiredItems - state.CompletedRequiredItems) + " pendência(s) obrigatória(s).";
                        pendRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                    }

                    foreach (var item in state.Items)
                    {
                        var row = new GameObject("Item_" + item.ItemId);
                        row.transform.SetParent(block.transform, false);
                        var rowRt = row.AddComponent<RectTransform>();
                        rowRt.sizeDelta = new Vector2(0, 22);

                        var checkGo = new GameObject("Check");
                        checkGo.transform.SetParent(row.transform, false);
                        var checkRt = checkGo.AddComponent<RectTransform>();
                        checkRt.anchorMin = new Vector2(0, 0.5f);
                        checkRt.anchorMax = new Vector2(0, 0.5f);
                        checkRt.pivot = new Vector2(0, 0.5f);
                        checkRt.sizeDelta = new Vector2(18, 18);
                        checkRt.anchoredPosition = Vector2.zero;
                        var checkImg = checkGo.AddComponent<Image>();
                        checkImg.color = item.IsCompleted ? new Color(0.3f, 0.8f, 0.4f) : new Color(0.9f, 0.9f, 0.9f);
                        var checkBtn = checkGo.AddComponent<Button>();
                        checkBtn.targetGraphic = checkImg;
                        var itemId = item.ItemId;
                        var isCompleted = item.IsCompleted;
                        checkBtn.onClick.AddListener(() =>
                        {
                            if (isCompleted)
                                ProducerPreparationChecklistController.MarkItemIncomplete(orderId, itemId);
                            else
                                ProducerPreparationChecklistController.MarkItemCompleted(orderId, itemId, "Producer");
                            Refresh();
                        });

                        var textGo = new GameObject("Text");
                        textGo.transform.SetParent(row.transform, false);
                        var textRt = textGo.AddComponent<RectTransform>();
                        textRt.anchorMin = new Vector2(0, 0);
                        textRt.anchorMax = new Vector2(1, 1);
                        textRt.offsetMin = new Vector2(22, 0);
                        textRt.offsetMax = new Vector2(0, 0);
                        var t = textGo.AddComponent<Text>();
                        t.font = font;
                        t.fontSize = 10;
                        t.text = (item.IsRequired ? "[Obrigatório] " : "") + item.Title + (item.IsCompleted ? " ✓ " + item.CompletedByRole : "");
                    }

                    var confirmBtn = new GameObject("ConfirmBtn");
                    confirmBtn.transform.SetParent(block.transform, false);
                    var confirmRt = confirmBtn.AddComponent<RectTransform>();
                    confirmRt.sizeDelta = new Vector2(0, 28);
                    var confirmImg = confirmBtn.AddComponent<Image>();
                    confirmImg.color = state.CompletedRequiredItems >= state.RequiredItems ? new Color(0.3f, 0.7f, 0.4f) : new Color(0.6f, 0.6f, 0.6f);
                    var confirmButton = confirmBtn.AddComponent<Button>();
                    confirmButton.targetGraphic = confirmImg;
                    confirmButton.interactable = state.CompletedRequiredItems >= state.RequiredItems;
                    confirmButton.onClick.AddListener(() =>
                    {
                        if (ProducerPreparationChecklistController.ConfirmPreparation(orderId, "Preparação confirmada (mock)."))
                            Refresh();
                    });
                    var confirmTextGo = new GameObject("Text");
                    confirmTextGo.transform.SetParent(confirmBtn.transform, false);
                    var confirmTextRt = confirmTextGo.AddComponent<RectTransform>();
                    confirmTextRt.anchorMin = Vector2.zero;
                    confirmTextRt.anchorMax = Vector2.one;
                    confirmTextRt.offsetMin = Vector2.zero;
                    confirmTextRt.offsetMax = Vector2.zero;
                    var confirmText = confirmTextGo.AddComponent<Text>();
                    confirmText.text = state.CompletedRequiredItems >= state.RequiredItems ? "Confirmar preparação final" : "Conclua os itens obrigatórios para confirmar";
                    confirmText.font = font;
                    confirmText.fontSize = 11;
                    confirmText.alignment = TextAnchor.MiddleCenter;
                }
            }
        }

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