using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;
using EventsAppQuest.Web.Producer.Application;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel no CRM do hotel: gerar pedido operacional, reenviar handoff, ver status do handoff (mock).
    /// </summary>
    public class HandoffToProducerPanel : 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 data = WebRuntimeContext.DataService;
            if (data == 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, 20);
            var labelText = label.AddComponent<Text>();
            labelText.text = "Handoff para produtor";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var opp in data.GetOpportunities())
            {
                var oppId = opp.Id;
                var btn = new GameObject("Generate_" + oppId);
                btn.transform.SetParent(_content, false);
                var btnRt = btn.AddComponent<RectTransform>();
                btnRt.sizeDelta = new Vector2(0, 26);
                var btnImg = btn.AddComponent<Image>();
                btnImg.color = new Color(0.4f, 0.7f, 0.5f, 1f);
                var b = btn.AddComponent<Button>();
                var tGo = new GameObject("Text");
                tGo.transform.SetParent(btn.transform, false);
                var t = tGo.AddComponent<Text>();
                t.text = "[Gerar pedido operacional] " + opp.Title;
                t.font = font;
                t.fontSize = 11;
                t.alignment = TextAnchor.MiddleLeft;
                var tRt = tGo.GetComponent<RectTransform>();
                tRt.anchorMin = Vector2.zero;
                tRt.anchorMax = Vector2.one;
                tRt.offsetMin = new Vector2(4, 0);
                tRt.offsetMax = Vector2.zero;
                b.targetGraphic = btnImg;
                b.onClick.AddListener(() => OnGenerate(oppId));
            }

            var statusLabel = new GameObject("StatusLabel");
            statusLabel.transform.SetParent(_content, false);
            var statusLabelRt = statusLabel.AddComponent<RectTransform>();
            statusLabelRt.sizeDelta = new Vector2(0, 22);
            var statusLabelText = statusLabel.AddComponent<Text>();
            statusLabelText.text = "Status do handoff (pedidos gerados):";
            statusLabelText.font = font;
            statusLabelText.fontSize = 12;
            statusLabelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var row = new GameObject("HandoffStatus");
                row.transform.SetParent(_content, false);
                var rowRt = row.AddComponent<RectTransform>();
                rowRt.sizeDelta = new Vector2(0, 32);
                var rowText = row.AddComponent<Text>();
                rowText.text = $"{order.OrderId} | Oport. {order.OpportunityId} | {HandoffIndicatorHelper.GetIndicatorLabel(order)}\n  Resumo: {order.OrderSummary}";
                rowText.font = font;
                rowText.fontSize = 10;
            }
        }

        private void OnGenerate(string opportunityId)
        {
            var data = WebRuntimeContext.DataService;
            if (data == null) return;
            var order = HotelToProducerHandoffService.GenerateOrder(
                opportunityId,
                data.GetOpportunities(),
                data.GetProposals(),
                data.GetSessions());
            if (order != null)
                WebRuntimeContext.NotifyDataChanged();
            Refresh();
        }

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