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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel no CRM do hotel: relatório final do pedido, resumo da execução, ajustes, issues/bloqueios, conclusão operacional.
    /// </summary>
    public class OrderFinalReportPanel : 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 = "Relatório final de execução";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in HandoffStore.GetOrders())
            {
                var orderId = order.OrderId;
                var report = ProducerExecutionFinalReportController.GetReport(orderId);
                var indicator = FinalReportIndicatorHelper.GetHotelIndicator(orderId);
                var completionLabel = report != null ? FinalReportIndicatorHelper.GetCompletionSummaryLabel(report) : "—";

                var block = new GameObject("FinalReport_" + 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} | {completionLabel}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                if (report == null)
                {
                    var noReport = new GameObject("NoReport");
                    noReport.transform.SetParent(block.transform, false);
                    var noText = noReport.AddComponent<Text>();
                    noText.font = font;
                    noText.fontSize = 10;
                    noText.text = "Relatório final ainda não disponível (produtor deve gerar e concluir operacionalmente).";
                    noReport.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                    continue;
                }

                var statusRow = new GameObject("Status");
                statusRow.transform.SetParent(block.transform, false);
                var statusText = statusRow.AddComponent<Text>();
                statusText.font = font;
                statusText.fontSize = 10;
                statusText.text = "Concluído operacionalmente: " + (report.ClosedByProducerAt.HasValue ? report.ClosedByProducerAt.Value.ToString("yyyy-MM-dd HH:mm") : "Não");
                statusRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                var summaryRow = new GameObject("Summary");
                summaryRow.transform.SetParent(block.transform, false);
                var sumText = summaryRow.AddComponent<Text>();
                sumText.font = font;
                sumText.fontSize = 10;
                sumText.text = "Resumo final: " + (report.FinalSummary ?? "—");
                summaryRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                var deliveredRow = new GameObject("Delivered");
                deliveredRow.transform.SetParent(block.transform, false);
                var delText = deliveredRow.AddComponent<Text>();
                delText.font = font;
                delText.fontSize = 10;
                delText.text = "Entregue: " + (report.DeliveredScopeSummary ?? "—");
                deliveredRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                if (!string.IsNullOrEmpty(report.AdjustmentsMade))
                {
                    var adjRow = new GameObject("Adjustments");
                    adjRow.transform.SetParent(block.transform, false);
                    var adjText = adjRow.AddComponent<Text>();
                    adjText.font = font;
                    adjText.fontSize = 10;
                    adjText.text = "Ajustes feitos: " + report.AdjustmentsMade;
                    adjRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }

                if (!string.IsNullOrEmpty(report.BlockingIssuesEncountered))
                {
                    var issRow = new GameObject("Issues");
                    issRow.transform.SetParent(block.transform, false);
                    var issText = issRow.AddComponent<Text>();
                    issText.font = font;
                    issText.fontSize = 10;
                    issText.text = "Issues/Bloqueios: " + report.BlockingIssuesEncountered;
                    issRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }

                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 conclusão: " + (report.CompletionNotes ?? "—");
                notesRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                if (report.ClosedByProducerAt.HasValue && !report.HotelAcknowledgedAt.HasValue)
                {
                    var btnRow = new GameObject("AckRow");
                    btnRow.transform.SetParent(block.transform, false);
                    btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 26);
                    var ackBtn = new GameObject("AckBtn");
                    ackBtn.transform.SetParent(btnRow.transform, false);
                    var rt = ackBtn.AddComponent<RectTransform>();
                    rt.sizeDelta = new Vector2(160, 22);
                    var img = ackBtn.AddComponent<Image>();
                    img.color = new Color(0.3f, 0.6f, 0.85f);
                    var btn = ackBtn.AddComponent<Button>();
                    btn.targetGraphic = img;
                    btn.onClick.AddListener(() =>
                    {
                        ProducerExecutionFinalReportController.SetHotelAcknowledged(orderId);
                        Refresh();
                    });
                    var tGo = new GameObject("Text");
                    tGo.transform.SetParent(ackBtn.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 = "Reconhecer fechamento";
                    t.font = font;
                    t.fontSize = 10;
                    t.alignment = TextAnchor.MiddleCenter;
                }
                else if (report.HotelAcknowledgedAt.HasValue)
                {
                    var ackRow = new GameObject("AckDone");
                    ackRow.transform.SetParent(block.transform, false);
                    var ackText = ackRow.AddComponent<Text>();
                    ackText.font = font;
                    ackText.fontSize = 10;
                    ackText.text = "Revisão do hotel feita em: " + report.HotelAcknowledgedAt.Value.ToString("yyyy-MM-dd HH:mm");
                    ackRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
            }
        }

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