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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel de favoritos/watchlist: lista observados, favoritos, fixados, motivo, notas.
    /// </summary>
    public class EventCycleWatchlistPanel : 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 watchState = EventCycleWatchlistController.GetWatchlistState(priorityState);

            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 = "Favoritos e casos observados (watchlist)";
            titleText.font = font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            AddBlock(_content, font, "Resumo", watchState.WatchlistSummary ?? "—");
            AddBlock(_content, font, "Última atualização", watchState.LastUpdatedAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            if (watchState.Items != null && watchState.Items.Count > 0)
            {
                foreach (var w in watchState.Items)
                {
                    var row = new GameObject("Watch_" + w.CycleId);
                    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 fav = w.IsFavorite ? " ★" : "";
                    var pin = w.IsPinned ? " 📌" : "";
                    t1.text = $"{w.Title}{fav}{pin} [{w.CycleId}]";
                    line1.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);

                    var line2 = new GameObject("Line2");
                    line2.transform.SetParent(row.transform, false);
                    var t2 = line2.AddComponent<Text>();
                    t2.font = font;
                    t2.fontSize = 9;
                    t2.text = "Motivo: " + (w.WatchReason ?? "—") + (string.IsNullOrEmpty(w.Notes) ? "" : " | Notas: " + w.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, w.IsFavorite ? "Desfavoritar" : "Favorito", font, 90, () => { EventCycleWatchlistController.SetFavorite(w.CycleId, !w.IsFavorite); Refresh(); });
                    CreateSmallButton(btnRow.transform, w.IsPinned ? "Desfixar" : "Fixar", font, 60, () => { EventCycleWatchlistController.SetPinned(w.CycleId, !w.IsPinned); Refresh(); });
                    CreateSmallButton(btnRow.transform, "Remover", font, 70, () => { EventCycleWatchlistController.RemoveFromWatchlist(w.CycleId); Refresh(); });
                    btnRow.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
                }
            }

            var notWatched = priorityState?.Items?.Where(p => !EventCycleWatchlistController.IsWatched(p.CycleId)).ToList();
            if (notWatched != null && notWatched.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 à watchlist:";
                addHeader.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
                foreach (var p in notWatched.Take(15))
                {
                    var addRow = new GameObject("Add_" + p.CycleId);
                    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;
                    labelText.text = p.Title + " [" + p.CycleId + "]";
                    var le = label.AddComponent<LayoutElement>();
                    le.flexibleWidth = 1;
                    CreateSmallButton(addRow.transform, "Adicionar", font, 80, () => { EventCycleWatchlistController.AddToWatchlist(p.CycleId, p.OpportunityId, p.Title, null); 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);
        }
    }
}
