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

namespace EventsAppQuest.Web.Producer.Presentation
{
    /// <summary>
    /// Detalhes do pedido: origem (proposta, sessão Quest), escopo (tema, pacote, itens, hotspots), notas do comercial.
    /// </summary>
    public class ProducerOrderDetailsView : 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");
            foreach (var order in service.GetOrders())
            {
                var go = new GameObject("OrderDetails");
                go.transform.SetParent(_content, false);
                var rt = go.AddComponent<RectTransform>();
                rt.sizeDelta = new Vector2(0, 140);
                var text = go.AddComponent<Text>();
                text.text = $"Pedido {order.OrderId}\n";
                text.text += $"Origem: Proposta {order.ProposalId} | Sessão Quest: {(string.IsNullOrEmpty(order.SessionId) ? "—" : order.SessionId)} | Oportunidade {order.OpportunityId}\n";
                text.text += $"Recomendação: {order.RecommendedProposalId ?? "—"} | Selecionada: {order.SelectedProposalId ?? "—"}\n";
                text.text += $"Escopo: {order.EventCategory ?? "—"} | Tema: {order.ThemeLabel ?? "—"} | Pacote: {order.SelectedCommercialPackageLabel ?? "—"}\n";
                text.text += $"Itens: {string.Join(", ", order.RequiredShowroomItems.Take(5))}{(order.RequiredShowroomItems.Count > 5 ? "…" : "")}\n";
                text.text += $"Hotspots/destaques: {string.Join(", ", order.KeyHotspots)}\n";
                text.text += $"Notas do comercial: {string.Join(" | ", order.KeyNotesFromSales)}\n";
                text.text += $"Resumo: {order.OrderSummary ?? "—"}\n";
                text.text += $"Indicador: {HandoffIndicatorHelper.GetIndicatorLabel(order)} | {(order.RequiresClarification ? "Esclarecimento: " + (order.ClarificationReason ?? "—") : "")}";
                text.font = font;
                text.fontSize = 10;
            }
        }

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