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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel da trilha de decisões executivas: listar, adicionar, editar, remover; vínculo a snapshot/contexto.
    /// </summary>
    public class EventCycleExecutiveDecisionTrailPanel : MonoBehaviour, IWebContentRoot
    {
        private Transform _content;
        private string _editingDecisionId;

        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 orders = HandoffStore.GetOrders();
            var opportunities = data.GetOpportunities();
            var proposals = data.GetProposals();
            var sessions = data.GetSessions();
            var followUps = data.GetFollowUpTasks();
            var portfolioState = EventCyclePortfolioPriorityController.BuildPortfolioPriority(orders, opportunities, proposals, sessions, followUps);
            var globalState = EventCycleExecutiveDecisionTrailController.GetGlobalTrailState();

            var titleRow = new GameObject("TitleRow");
            titleRow.transform.SetParent(_content, false);
            titleRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 26);
            var titleText = titleRow.AddComponent<Text>();
            titleText.text = "Trilha gerencial do caso — Histórico de decisões executivas";
            titleText.font = font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            AddBlock(_content, font, "Resumo", globalState.DecisionTrailSummary ?? "—");
            AddBlock(_content, font, "Total de decisões", globalState.TotalDecisions.ToString());
            AddBlock(_content, font, "Última decisão em", globalState.LastDecisionAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            if (portfolioState?.Items == null || portfolioState.Items.Count == 0)
            {
                var empty = new GameObject("Empty");
                empty.transform.SetParent(_content, false);
                var emptyText = empty.AddComponent<Text>();
                emptyText.font = font;
                emptyText.fontSize = 11;
                emptyText.text = "Nenhum ciclo na carteira. Gere pedidos a partir de oportunidades.";
                empty.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                return;
            }

            foreach (var item in portfolioState.Items)
            {
                var cycleId = item.CycleId;
                var trailState = EventCycleExecutiveDecisionTrailController.GetTrailState(cycleId);

                var block = new GameObject("Cycle_" + cycleId);
                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.fontStyle = FontStyle.Bold;
                headerText.text = $"{item.Title} [{cycleId}] | decisões: {trailState.TotalDecisions} | última: {(trailState.LastDecisionAt?.ToString("yyyy-MM-dd HH:mm") ?? "—")}";
                header.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);

                if (trailState.Decisions != null)
                {
                    foreach (var d in trailState.Decisions)
                    {
                        if (d == null) continue;
                        if (_editingDecisionId == d.DecisionId)
                        {
                            AddEditForm(block.transform, font, d);
                            continue;
                        }
                        var row = new GameObject("Dec_" + d.DecisionId);
                        row.transform.SetParent(block.transform, false);
                        var rowLayout = row.AddComponent<VerticalLayoutGroup>();
                        rowLayout.spacing = 2;
                        rowLayout.childForceExpandHeight = false;
                        rowLayout.childForceExpandWidth = true;

                        var line1 = new GameObject("Line1");
                        line1.transform.SetParent(row.transform, false);
                        var t1 = line1.AddComponent<Text>();
                        t1.font = font;
                        t1.fontSize = 11;
                        t1.text = $"{d.Title} — {d.DecisionCategory} | {d.DecisionOutcome} | {d.DecidedByRole}";
                        line1.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);

                        var line2 = new GameObject("Line2");
                        line2.transform.SetParent(row.transform, false);
                        var t2 = line2.AddComponent<Text>();
                        t2.font = font;
                        t2.fontSize = 9;
                        t2.text = (d.Summary ?? "—") + " | Razão: " + (d.DecisionReason ?? "—");
                        line2.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);

                        var line3 = new GameObject("Line3");
                        line3.transform.SetParent(row.transform, false);
                        var t3 = line3.AddComponent<Text>();
                        t3.font = font;
                        t3.fontSize = 9;
                        t3.text = "Snapshot: " + (d.RelatedSnapshotId ?? "—") + " | Secção: " + (d.RelatedSectionKey ?? "—") + " | Caso: " + d.CycleId + " | " + (d.CreatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");
                        line3.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 12);

                        var btnRow = new GameObject("BtnRow");
                        btnRow.transform.SetParent(row.transform, false);
                        var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
                        hLayout.spacing = 4;
                        hLayout.childForceExpandWidth = false;
                        CreateSmallButton(btnRow.transform, "Editar", font, 60, () => { _editingDecisionId = d.DecisionId; Refresh(); });
                        CreateSmallButton(btnRow.transform, "Remover", font, 70, () => { EventCycleExecutiveDecisionTrailController.RemoveDecision(d.DecisionId); WebRuntimeContext.NotifyDataChanged(); Refresh(); });
                        btnRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
                    }
                }

                var addRow = new GameObject("Add_" + cycleId);
                addRow.transform.SetParent(block.transform, false);
                var addLayout = addRow.AddComponent<HorizontalLayoutGroup>();
                addLayout.spacing = 6;
                addLayout.childForceExpandWidth = false;
                var addLabel = new GameObject("Label");
                addLabel.transform.SetParent(addRow.transform, false);
                var addLabelText = addLabel.AddComponent<Text>();
                addLabelText.font = font;
                addLabelText.fontSize = 10;
                addLabelText.text = "Adicionar decisão (padrão): ";
                var le = addLabel.AddComponent<LayoutElement>();
                le.flexibleWidth = 1;
                CreateSmallButton(addRow.transform, "Nova decisão", font, 110, () =>
                {
                    EventCycleExecutiveDecisionTrailController.AddDecision(cycleId, "Nova decisão", "", EventCycleExecutiveDecisionCategory.CommercialDirection, EventCycleExecutiveDecisionOutcome.Approved, "", EventCycleExecutiveDecisionRole.InternalAdmin, null, null, null);
                    WebRuntimeContext.NotifyDataChanged();
                    Refresh();
                });
                addRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            }
        }

        private void AddEditForm(Transform parent, Font font, EventCycleExecutiveDecision d)
        {
            var editBlock = new GameObject("EditForm");
            editBlock.transform.SetParent(parent, false);
            var layout = editBlock.AddComponent<VerticalLayoutGroup>();
            layout.spacing = 4;
            layout.childForceExpandHeight = false;
            layout.childForceExpandWidth = true;

            var titleLabel = new GameObject("TitleLabel");
            titleLabel.transform.SetParent(editBlock.transform, false);
            var titleLabelText = titleLabel.AddComponent<Text>();
            titleLabelText.font = font;
            titleLabelText.fontSize = 10;
            titleLabelText.text = "Título:";
            titleLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

            var titleRow = new GameObject("TitleInputRow");
            titleRow.transform.SetParent(editBlock.transform, false);
            titleRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            var titleInput = CreateSimpleInput(titleRow.transform, font, d.Title ?? "");

            var summaryLabel = new GameObject("SummaryLabel");
            summaryLabel.transform.SetParent(editBlock.transform, false);
            var summaryLabelText = summaryLabel.AddComponent<Text>();
            summaryLabelText.font = font;
            summaryLabelText.fontSize = 10;
            summaryLabelText.text = "Resumo:";
            summaryLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
            var summaryRow = new GameObject("SummaryInputRow");
            summaryRow.transform.SetParent(editBlock.transform, false);
            summaryRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            var summaryInput = CreateSimpleInput(summaryRow.transform, font, d.Summary ?? "");

            var reasonLabel = new GameObject("ReasonLabel");
            reasonLabel.transform.SetParent(editBlock.transform, false);
            var reasonLabelText = reasonLabel.AddComponent<Text>();
            reasonLabelText.font = font;
            reasonLabelText.fontSize = 10;
            reasonLabelText.text = "Razão:";
            reasonLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
            var reasonRow = new GameObject("ReasonInputRow");
            reasonRow.transform.SetParent(editBlock.transform, false);
            reasonRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            var reasonInput = CreateSimpleInput(reasonRow.transform, font, d.DecisionReason ?? "");

            var snapLabel = new GameObject("SnapLabel");
            snapLabel.transform.SetParent(editBlock.transform, false);
            var snapLabelText = snapLabel.AddComponent<Text>();
            snapLabelText.font = font;
            snapLabelText.fontSize = 10;
            snapLabelText.text = "Snapshot relacionado (opcional):";
            snapLabel.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
            var snapRow = new GameObject("SnapInputRow");
            snapRow.transform.SetParent(editBlock.transform, false);
            snapRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            var snapInput = CreateSimpleInput(snapRow.transform, font, d.RelatedSnapshotId ?? "");

            var btnRow = new GameObject("EditBtnRow");
            btnRow.transform.SetParent(editBlock.transform, false);
            var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
            hLayout.spacing = 6;
            hLayout.childForceExpandWidth = false;
            CreateSmallButton(btnRow.transform, "Guardar", font, 70, () =>
            {
                EventCycleExecutiveDecisionTrailController.UpdateDecision(d.DecisionId, titleInput.text, summaryInput.text, null, null, reasonInput.text, null, string.IsNullOrEmpty(snapInput.text) ? null : snapInput.text, null, null);
                _editingDecisionId = null;
                WebRuntimeContext.NotifyDataChanged();
                Refresh();
            });
            CreateSmallButton(btnRow.transform, "Cancelar", font, 80, () => { _editingDecisionId = null; Refresh(); });
            btnRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
        }

        private static InputField CreateSimpleInput(Transform parent, Font font, string initial)
        {
            var go = new GameObject("Input");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.offsetMin = Vector2.zero;
            rt.offsetMax = Vector2.zero;
            var img = go.AddComponent<Image>();
            img.color = new Color(1f, 1f, 1f, 0.9f);
            var input = go.AddComponent<InputField>();
            input.text = initial ?? "";
            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;
            return input;
        }

        private static void AddBlock(Transform parent, Font font, string title, string content)
        {
            var go = new GameObject("Block_" + title);
            go.transform.SetParent(parent, false);
            var text = go.AddComponent<Text>();
            text.font = font;
            text.fontSize = 10;
            text.text = title + ": " + (content ?? "—");
            go.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
        }

        private static GameObject CreateSmallButton(Transform parent, string label, Font font, float width, System.Action onClick)
        {
            var go = new GameObject("Btn_" + label);
            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 = label;
            t.font = font;
            t.fontSize = 9;
            t.alignment = TextAnchor.MiddleCenter;
            return go;
        }

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