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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel no CRM do hotel: status de execução do pedido, progresso, últimos updates, issues/bloqueios, conclusão.
    /// </summary>
    public class OrderExecutionPanel : 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 = "Status de execução do pedido";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var orderId = order.OrderId;
                var state = ProducerExecutionTrackingController.GetState(orderId);
                var updates = ProducerExecutionTrackingController.GetUpdates(orderId, 15).ToList();

                var block = new GameObject("Execution_" + 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} | {state.ExecutionStatus} | {state.ProgressPercent}% | {(state.IsPaused ? "Pausado" : "")} {(state.IsCompleted ? "Concluído" : "")} {(state.HasIssues ? "Com issues" : "")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                var progressRow = new GameObject("Progress");
                progressRow.transform.SetParent(block.transform, false);
                var progressText = progressRow.AddComponent<Text>();
                progressText.font = font;
                progressText.fontSize = 10;
                progressText.text = "Progresso: " + state.ProgressPercent + "% — " + (state.CurrentExecutionSummary ?? "—");
                progressRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                if (state.IsCompleted && !string.IsNullOrEmpty(state.CompletionSummary))
                {
                    var completionRow = new GameObject("Completion");
                    completionRow.transform.SetParent(block.transform, false);
                    var completionText = completionRow.AddComponent<Text>();
                    completionText.font = font;
                    completionText.fontSize = 10;
                    completionText.fontStyle = FontStyle.Bold;
                    completionText.text = "Conclusão: " + state.CompletionSummary;
                    completionRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                }

                var issuesRow = new GameObject("Issues");
                issuesRow.transform.SetParent(block.transform, false);
                var issuesText = issuesRow.AddComponent<Text>();
                issuesText.font = font;
                issuesText.fontSize = 10;
                issuesText.text = state.HasIssues ? "Existem issues reportadas." : "Sem issues.";
                if (state.ExecutionStatus == ProducerExecutionStatus.Blocked)
                    issuesText.text += " Execução bloqueada.";
                issuesRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                var updatesLabel = new GameObject("UpdatesLabel");
                updatesLabel.transform.SetParent(block.transform, false);
                var ulText = updatesLabel.AddComponent<Text>();
                ulText.font = font;
                ulText.fontSize = 10;
                ulText.text = updates.Count == 0 ? "Sem updates." : string.Join("\n", updates.Select(u => $"[{u.UpdateType}] {u.Title}: {u.Summary} {(u.IsIssue ? "(issue)" : "")} {(u.IsBlocking ? "(bloqueio)" : "")}"));
                updatesLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, Mathf.Max(18, updates.Count * 12));
            }
        }

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