using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;
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: aceite final da entrega, rejeitar/solicitar ajuste, nota final, encerramento do ciclo.
    /// </summary>
    public class OrderFinalAcceptancePanel : 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);
            label.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var labelText = label.AddComponent<Text>();
            labelText.text = "Aceite final do hotel e encerramento do ciclo";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var orderId = order.OrderId;
                var canReview = HotelFinalAcceptanceController.CanHotelReviewFinal(orderId);
                var state = HotelFinalAcceptanceController.GetOrCreateState(orderId);
                var indicator = HotelFinalAcceptanceIndicatorHelper.GetHotelAcceptanceIndicator(orderId);

                var block = new GameObject("FinalAcceptance_" + 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} | {indicator} | {(state != null && state.IsOrderCycleClosed ? "Ciclo encerrado" : "—")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                if (!canReview)
                {
                    var waitRow = new GameObject("Wait");
                    waitRow.transform.SetParent(block.transform, false);
                    var waitText = waitRow.AddComponent<Text>();
                    waitText.font = font;
                    waitText.fontSize = 10;
                    waitText.text = "Aguardando relatório final e conclusão operacional do produtor.";
                    waitRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                    continue;
                }

                if (state != null && !string.IsNullOrEmpty(state.FinalAcceptanceSummary))
                {
                    var sumRow = new GameObject("Summary");
                    sumRow.transform.SetParent(block.transform, false);
                    var sumText = sumRow.AddComponent<Text>();
                    sumText.font = font;
                    sumText.fontSize = 10;
                    sumText.text = "Resumo aceite: " + state.FinalAcceptanceSummary;
                    sumRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
                if (state != null && !string.IsNullOrEmpty(state.HotelAcceptanceNotes))
                {
                    var notesRow = new GameObject("Notes");
                    notesRow.transform.SetParent(block.transform, false);
                    var notesText = notesRow.AddComponent<Text>();
                    notesText.font = font;
                    notesText.fontSize = 10;
                    notesText.text = "Notas: " + state.HotelAcceptanceNotes;
                    notesRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
                if (state != null && state.AcceptedAt.HasValue)
                {
                    var dateRow = new GameObject("AcceptedAt");
                    dateRow.transform.SetParent(block.transform, false);
                    var dateText = dateRow.AddComponent<Text>();
                    dateText.font = font;
                    dateText.fontSize = 10;
                    dateText.text = "Aceite em: " + state.AcceptedAt.Value.ToString("yyyy-MM-dd HH:mm");
                    dateRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
                if (state != null && state.RejectedAt.HasValue)
                {
                    var dateRow = new GameObject("RejectedAt");
                    dateRow.transform.SetParent(block.transform, false);
                    var dateText = dateRow.AddComponent<Text>();
                    dateText.font = font;
                    dateText.fontSize = 10;
                    dateText.text = "Rejeitado em: " + state.RejectedAt.Value.ToString("yyyy-MM-dd HH:mm");
                    dateRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
                if (state != null && state.ClosedAt.HasValue)
                {
                    var closedRow = new GameObject("ClosedAt");
                    closedRow.transform.SetParent(block.transform, false);
                    var closedText = closedRow.AddComponent<Text>();
                    closedText.font = font;
                    closedText.fontSize = 10;
                    closedText.fontStyle = FontStyle.Bold;
                    closedText.text = "Ciclo encerrado em: " + state.ClosedAt.Value.ToString("yyyy-MM-dd HH:mm");
                    closedRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }

                var btnRow = new GameObject("BtnRow");
                btnRow.transform.SetParent(block.transform, false);
                btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 28);
                var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
                hLayout.spacing = 4;
                hLayout.childForceExpandWidth = false;
                hLayout.childForceExpandHeight = true;

                if (state != null && (state.AcceptanceStatus == HotelFinalAcceptanceStatus.PendingReview || state.AcceptanceStatus == HotelFinalAcceptanceStatus.NeedsAdjustment))
                {
                    CreateSmallButton(btnRow.transform, "Aceitar entrega", font, 110, () =>
                    {
                        HotelFinalAcceptanceController.AcceptFinalDelivery(orderId, "Entrega aceite.", null);
                        Refresh();
                    });
                    CreateSmallButton(btnRow.transform, "Rejeitar", font, 70, () =>
                    {
                        HotelFinalAcceptanceController.RejectFinalDelivery(orderId, "Entrega rejeitada.", null);
                        Refresh();
                    });
                    CreateSmallButton(btnRow.transform, "Solicitar ajuste", font, 110, () =>
                    {
                        HotelFinalAcceptanceController.RequestFinalAdjustment(orderId, "Ajuste final solicitado.", null);
                        Refresh();
                    });
                }

                if (state != null && (state.AcceptanceStatus == HotelFinalAcceptanceStatus.Accepted || state.AcceptanceStatus == HotelFinalAcceptanceStatus.Rejected) && !state.IsOrderCycleClosed)
                {
                    var oid = orderId;
                    CreateSmallButton(btnRow.transform, "Encerrar ciclo", font, 100, () =>
                    {
                        HotelFinalAcceptanceController.CloseOrderCycle(oid, null);
                        var order = HandoffStore.GetOrderById(oid);
                        if (order != null && !string.IsNullOrEmpty(order.OpportunityId) && WebRuntimeContext.DataService is IMockWebDataService ds)
                            ds.MarkOpportunityOrderCycleClosed(order.OpportunityId);
                        Refresh();
                    });
                }
            }
        }

        private static Button CreateSmallButton(Transform parent, string text, Font font, float width, System.Action onClick)
        {
            var go = new GameObject("Btn_" + text);
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(width, 22);
            var le = go.AddComponent<LayoutElement>();
            le.preferredWidth = width;
            le.preferredHeight = 22;
            var img = go.AddComponent<Image>();
            img.color = new Color(0.4f, 0.7f, 0.5f);
            var btn = go.AddComponent<Button>();
            btn.targetGraphic = img;
            btn.onClick.AddListener(() => onClick?.Invoke());
            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 = text;
            t.font = font;
            t.fontSize = 9;
            t.alignment = TextAnchor.MiddleCenter;
            return btn;
        }

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