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

namespace EventsAppQuest.Web.Producer.Presentation
{
    /// <summary>
    /// Vista no painel do produtor: relatório final de execução, gerar relatório, revisar, concluir operacionalmente.
    /// </summary>
    public class ProducerFinalReportView : 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");

            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 = "Conclusão operacional e relatório final";
            labelText.font = font;
            labelText.fontSize = 14;
            labelText.fontStyle = FontStyle.Bold;

            foreach (var order in service.GetOrders())
            {
                var orderId = order.OrderId;
                var report = ProducerExecutionFinalReportController.GetReport(orderId);
                var execState = ProducerExecutionTrackingController.GetState(orderId);
                var indicator = FinalReportIndicatorHelper.GetProducerIndicator(orderId);

                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} | Execução: {execState.ExecutionStatus} {execState.ProgressPercent}%";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                if (report == null)
                {
                    var genBtn = CreateButton(block.transform, "Gerar relatório final", font, () =>
                    {
                        ProducerExecutionFinalReportController.GenerateReport(orderId);
                        Refresh();
                    });
                    genBtn.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
                    var hint = new GameObject("Hint");
                    hint.transform.SetParent(block.transform, false);
                    var hintText = hint.AddComponent<Text>();
                    hintText.font = font;
                    hintText.fontSize = 10;
                    hintText.text = "Gera o relatório a partir do estado actual da execução, checklist e pedido.";
                    hint.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                }
                else
                {
                    var summaryLabel = new GameObject("Summary");
                    summaryLabel.transform.SetParent(block.transform, false);
                    var sumText = summaryLabel.AddComponent<Text>();
                    sumText.font = font;
                    sumText.fontSize = 10;
                    sumText.text = "Resumo: " + (report.FinalSummary ?? "—");
                    summaryLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                    var deliveredLabel = new GameObject("Delivered");
                    deliveredLabel.transform.SetParent(block.transform, false);
                    var delText = deliveredLabel.AddComponent<Text>();
                    delText.font = font;
                    delText.fontSize = 10;
                    delText.text = "Entregue: " + (report.DeliveredScopeSummary ?? "—");
                    deliveredLabel.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: " + 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 btnRow = new GameObject("BtnRow");
                    btnRow.transform.SetParent(block.transform, false);
                    btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 26);
                    var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
                    hLayout.spacing = 4;
                    hLayout.childForceExpandWidth = false;
                    hLayout.childForceExpandHeight = true;

                    CreateSmallButton(btnRow.transform, "Atualizar relatório", font, 110, () =>
                    {
                        ProducerExecutionFinalReportController.GenerateReport(orderId);
                        Refresh();
                    });

                    if (!report.ClosedByProducerAt.HasValue)
                    {
                        CreateSmallButton(btnRow.transform, "Concluir operacionalmente", font, 140, () =>
                        {
                            ProducerExecutionFinalReportController.MarkOperationallyClosed(orderId);
                            Refresh();
                        });
                    }
                    else
                    {
                        var closedLabel = new GameObject("ClosedAt");
                        closedLabel.transform.SetParent(block.transform, false);
                        var closedText = closedLabel.AddComponent<Text>();
                        closedText.font = font;
                        closedText.fontSize = 10;
                        closedText.text = "Concluído em: " + report.ClosedByProducerAt.Value.ToString("yyyy-MM-dd HH:mm");
                        closedLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }

                    var hotelAcceptanceState = HotelFinalAcceptanceController.GetState(orderId);
                    var hotelAcceptanceLabel = HotelFinalAcceptanceIndicatorHelper.GetProducerAcceptanceIndicator(orderId);
                    var acceptanceRow = new GameObject("HotelAcceptance");
                    acceptanceRow.transform.SetParent(block.transform, false);
                    var accText = acceptanceRow.AddComponent<Text>();
                    accText.font = font;
                    accText.fontSize = 10;
                    accText.text = "Aceite final hotel: " + hotelAcceptanceLabel;
                    acceptanceRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    if (hotelAcceptanceState != null && !string.IsNullOrEmpty(hotelAcceptanceState.FinalAcceptanceSummary))
                    {
                        var accSumRow = new GameObject("HotelAcceptanceSummary");
                        accSumRow.transform.SetParent(block.transform, false);
                        var accSumText = accSumRow.AddComponent<Text>();
                        accSumText.font = font;
                        accSumText.fontSize = 10;
                        accSumText.text = "Resumo aceite: " + hotelAcceptanceState.FinalAcceptanceSummary;
                        accSumRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }
                    if (hotelAcceptanceState != null && !string.IsNullOrEmpty(hotelAcceptanceState.HotelAcceptanceNotes))
                    {
                        var accNotesRow = new GameObject("HotelAcceptanceNotes");
                        accNotesRow.transform.SetParent(block.transform, false);
                        var accNotesText = accNotesRow.AddComponent<Text>();
                        accNotesText.font = font;
                        accNotesText.fontSize = 10;
                        accNotesText.text = "Notas hotel: " + hotelAcceptanceState.HotelAcceptanceNotes;
                        accNotesRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                    }
                }
            }
        }

        private static Button CreateButton(Transform parent, string text, Font font, System.Action onClick)
        {
            var go = new GameObject("Btn");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>();
            var img = go.AddComponent<Image>();
            img.color = new Color(0.3f, 0.65f, 0.9f);
            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 = 11;
            t.alignment = TextAnchor.MiddleCenter;
            return btn;
        }

        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);
        }
    }
}
