using System.Collections.Generic;
using System.Linq;
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 de anotações gerenciais por caso: listar, criar, editar, remover, fixar; categoria e importância.
    /// </summary>
    public class EventCycleManagerNotesPanel : 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 orders = HandoffStore.GetOrders();
            var opportunities = data.GetOpportunities();
            var proposals = data.GetProposals();
            var sessions = data.GetSessions();
            var followUps = data.GetFollowUpTasks();
            var priorityState = EventCyclePortfolioPriorityController.BuildPortfolioPriority(orders, opportunities, proposals, sessions, followUps);
            var globalState = EventCycleManagerNotesController.GetGlobalNotesState();

            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 = "Anotações gerenciais por caso (contexto executivo)";
            titleText.font = font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            AddBlock(_content, font, "Resumo", globalState.NotesSummary ?? "—");
            AddBlock(_content, font, "Total de notas", globalState.TotalNotes.ToString());
            AddBlock(_content, font, "Última atualização", globalState.LastUpdatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            if (globalState.Notes != null && globalState.Notes.Count > 0)
            {
                var listHeader = new GameObject("ListHeader");
                listHeader.transform.SetParent(_content, false);
                var listHeaderText = listHeader.AddComponent<Text>();
                listHeaderText.font = font;
                listHeaderText.fontSize = 11;
                listHeaderText.fontStyle = FontStyle.Bold;
                listHeaderText.text = "Notas:";
                listHeader.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                foreach (var n in globalState.Notes)
                {
                    var row = new GameObject("Note_" + n.NoteId);
                    row.transform.SetParent(_content, false);
                    var layout = row.AddComponent<VerticalLayoutGroup>();
                    layout.spacing = 2;
                    layout.childForceExpandHeight = false;
                    layout.childForceExpandWidth = true;

                    var line1 = new GameObject("Line1");
                    line1.transform.SetParent(row.transform, false);
                    var t1 = line1.AddComponent<Text>();
                    t1.font = font;
                    t1.fontSize = 11;
                    var pinTag = n.IsPinned ? " 📌 " : "";
                    t1.text = $"{pinTag}[{n.CycleId}] {n.Title} — {n.NoteCategory} ({n.Importance})";
                    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 = (n.Summary ?? "—") + (string.IsNullOrEmpty(n.Notes) ? "" : " | " + n.Notes);
                    line2.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, n.IsPinned ? "Desfixar" : "Fixar", font, 60, () => { EventCycleManagerNotesController.SetNotePinned(n.NoteId, !n.IsPinned); Refresh(); });
                    CreateSmallButton(btnRow.transform, "Remover", font, 70, () => { EventCycleManagerNotesController.RemoveNote(n.NoteId); Refresh(); });
                    btnRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
                }
            }

            var cycleIds = priorityState?.Items?.Select(p => p.CycleId).Distinct().ToList() ?? new List<string>();
            if (cycleIds != null && cycleIds.Count > 0)
            {
                var addHeader = new GameObject("AddHeader");
                addHeader.transform.SetParent(_content, false);
                var addHeaderText = addHeader.AddComponent<Text>();
                addHeaderText.font = font;
                addHeaderText.fontSize = 11;
                addHeaderText.fontStyle = FontStyle.Bold;
                addHeaderText.text = "Adicionar nota ao caso:";
                addHeader.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                foreach (var cid in cycleIds.Take(10))
                {
                    var addRow = new GameObject("Add_" + cid);
                    addRow.transform.SetParent(_content, false);
                    var hLayout = addRow.AddComponent<HorizontalLayoutGroup>();
                    hLayout.spacing = 6;
                    hLayout.childForceExpandWidth = false;
                    var label = new GameObject("Label");
                    label.transform.SetParent(addRow.transform, false);
                    var labelText = label.AddComponent<Text>();
                    labelText.font = font;
                    labelText.fontSize = 10;
                    var title = priorityState?.Items?.FirstOrDefault(p => p.CycleId == cid)?.Title ?? cid;
                    labelText.text = title + " [" + cid + "]";
                    var le = label.AddComponent<LayoutElement>();
                    le.flexibleWidth = 1;
                    CreateSmallButton(addRow.transform, "Nova nota", font, 90, () => { EventCycleManagerNotesController.AddNote(cid, "Nova anotação", null, EventCycleManagerNoteCategory.InternalObservation, EventCycleManagerNoteImportance.Medium); Refresh(); });
                    addRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
                }
            }
        }

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