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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel no CRM do hotel: thread de comunicação por pedido, mensagens recentes, nova mensagem (mock), indicadores.
    /// </summary>
    public class OrderCommunicationPanel : MonoBehaviour, IWebContentRoot
    {
        private Transform _content;
        private const int RecentCount = 10;

        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 = "Comunicação operacional (por pedido)";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var orderId = order.OrderId;
                var messages = ProducerOrderCommunicationController.GetMessagesForOrder(orderId, RecentCount).ToList();
                var lastMessage = messages.Count > 0 ? messages[messages.Count - 1] : null;
                var commLabel = CommunicationIndicatorHelper.GetCommunicationLabel(order.AcceptanceStatus, order.RequiresClarification, lastMessage);

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

                var header = new GameObject("Header");
                header.transform.SetParent(orderBlock.transform, false);
                var headerRt = header.AddComponent<RectTransform>();
                headerRt.sizeDelta = new Vector2(0, 36);
                var headerText = header.AddComponent<Text>();
                headerText.text = $"{orderId} | {commLabel} | {(order.RequiresClarification ? "Dúvida pendente " : "")}{(lastMessage != null && lastMessage.MessageType == CommunicationMessageType.ClarificationResponse ? "| Resposta recebida" : "")}\nOrigem: Oport. {order.OpportunityId ?? "—"} | Proposta {order.ProposalId ?? "—"} | Sessão {order.SessionId ?? "—"} | Aceite: {order.AcceptanceStatus}";
                headerText.font = font;
                headerText.fontSize = 11;

                var msgArea = new GameObject("Messages");
                msgArea.transform.SetParent(orderBlock.transform, false);
                var msgAreaRt = msgArea.AddComponent<RectTransform>();
                msgAreaRt.sizeDelta = new Vector2(0, Mathf.Max(60, messages.Count * 18));
                var msgText = msgArea.AddComponent<Text>();
                msgText.font = font;
                msgText.fontSize = 10;
                msgText.text = string.Join("\n", messages.Select(m => $"[{m.SenderRole}] {m.MessageType}: {m.Content}"));
                if (messages.Count == 0) msgText.text = "(sem mensagens)";

                var inputRow = new GameObject("InputRow");
                inputRow.transform.SetParent(orderBlock.transform, false);
                var inputRowRt = inputRow.AddComponent<RectTransform>();
                inputRowRt.sizeDelta = new Vector2(0, 28);
                var inputField = CreateInputField(inputRow.transform, font);
                CreateSendButton(inputRow.transform, font, orderId, inputField, this);
            }
        }

        private static InputField CreateInputField(Transform parent, Font font)
        {
            var go = new GameObject("Input");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.anchorMin = new Vector2(0, 0);
            rt.anchorMax = new Vector2(1, 1);
            rt.offsetMin = new Vector2(0, 2);
            rt.offsetMax = new Vector2(-70, -2);
            var img = go.AddComponent<Image>();
            img.color = Color.white;
            var input = go.AddComponent<InputField>();

            var textGo = new GameObject("Text");
            textGo.transform.SetParent(go.transform, false);
            var textRt = textGo.AddComponent<RectTransform>();
            textRt.anchorMin = Vector2.zero;
            textRt.anchorMax = Vector2.one;
            textRt.offsetMin = new Vector2(4, 2);
            textRt.offsetMax = new Vector2(-4, -2);
            var text = textGo.AddComponent<Text>();
            text.font = font;
            text.fontSize = 11;
            text.supportRichText = false;
            input.textComponent = text;

            var placeGo = new GameObject("Placeholder");
            placeGo.transform.SetParent(go.transform, false);
            var placeRt = placeGo.AddComponent<RectTransform>();
            placeRt.anchorMin = Vector2.zero;
            placeRt.anchorMax = Vector2.one;
            placeRt.offsetMin = new Vector2(4, 2);
            placeRt.offsetMax = new Vector2(-4, -2);
            var place = placeGo.AddComponent<Text>();
            place.text = "Nova mensagem...";
            place.font = font;
            place.fontSize = 11;
            place.color = new Color(0.5f, 0.5f, 0.5f);
            input.placeholder = place;
            return input;
        }

        private static Button CreateSendButton(Transform parent, Font font, string orderId, InputField inputField, OrderCommunicationPanel panel)
        {
            var go = new GameObject("Send");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.anchorMin = new Vector2(1, 0);
            rt.anchorMax = new Vector2(1, 1);
            rt.pivot = new Vector2(1, 0.5f);
            rt.sizeDelta = new Vector2(64, 0);
            rt.anchoredPosition = Vector2.zero;
            var img = go.AddComponent<Image>();
            img.color = new Color(0.3f, 0.6f, 0.9f);
            var btn = go.AddComponent<Button>();
            btn.targetGraphic = img;

            var tGo = new GameObject("Text");
            tGo.transform.SetParent(go.transform, false);
            var tRt = tGo.AddComponent<RectTransform>();
            tRt.anchorMin = Vector2.zero;
            tRt.anchorMax = Vector2.one;
            tRt.offsetMin = Vector2.zero;
            tRt.offsetMax = Vector2.zero;
            var t = tGo.AddComponent<Text>();
            t.text = "Enviar";
            t.font = font;
            t.fontSize = 11;
            t.alignment = TextAnchor.MiddleCenter;

            btn.onClick.AddListener(() =>
            {
                var content = inputField != null && inputField.textComponent != null ? inputField.text : "";
                if (string.IsNullOrWhiteSpace(content)) content = "(nota)";
                ProducerOrderCommunicationController.AddGeneralNote(orderId, CommunicationParticipantRole.HotelSales, content.Trim());
                if (inputField != null) inputField.text = "";
                WebRuntimeContext.NotifyDataChanged();
                if (panel != null) panel.Refresh();
            });
            return btn;
        }

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