using System.Collections.Generic;
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 filtros executivos da carteira: listar filtros, aplicar, total filtrado, item prioritário do recorte, resumo.
    /// </summary>
    public class EventCyclePortfolioFilterPanel : 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 filteredState = EventCyclePortfolioFilterController.ApplyActiveFilterOrNone(priorityState);
            var availableFilters = EventCyclePortfolioFilterController.GetAvailableFilters();

            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 = "Filtros executivos da carteira";
            titleText.font = font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            var btnRow = new GameObject("BtnRow");
            btnRow.transform.SetParent(_content, false);
            btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
            var hLayout = btnRow.AddComponent<HorizontalLayoutGroup>();
            hLayout.spacing = 6;
            hLayout.childForceExpandWidth = false;
            CreateSmallButton(btnRow.transform, "Limpar filtro", font, 100, () => { EventCyclePortfolioFilterController.ClearActiveFilter(); Refresh(); });

            AddBlock(_content, font, "Filtros disponíveis", "Clique para aplicar um recorte.");
            foreach (var f in availableFilters)
            {
                var isActive = filteredState.ActiveFilter?.FilterId == f.FilterId;
                var btn = CreateSmallButton(_content, f.Name, font, 220, () => { EventCyclePortfolioFilterController.SetActiveFilter(f.FilterId); Refresh(); });
                if (isActive)
                {
                    var text = btn.GetComponentInChildren<Text>();
                    if (text != null) text.fontStyle = FontStyle.Bold;
                    var img = btn.GetComponent<Image>();
                    if (img != null) img.color = new Color(0.35f, 0.65f, 0.45f);
                }
            }

            AddBlock(_content, font, "Resumo do recorte", filteredState.FilterSummary ?? "—");
            AddBlock(_content, font, "Total filtrado", filteredState.FilteredCount.ToString());
            if (filteredState.HighestPriorityFilteredItem != null)
                AddBlock(_content, font, "Item mais crítico do recorte", $"{filteredState.HighestPriorityFilteredItem.Title} (score {filteredState.HighestPriorityFilteredItem.PriorityScore})");
            AddBlock(_content, font, "Última filtragem", filteredState.LastFilteredAt?.ToString("yyyy-MM-dd HH:mm") ?? "—");

            if (filteredState.FilteredItems != null && filteredState.FilteredItems.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 = "Itens no recorte:";
                listHeader.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                foreach (var item in filteredState.FilteredItems)
                {
                    var row = new GameObject("Item_" + item.CycleId);
                    row.transform.SetParent(_content, false);
                    var rowText = row.AddComponent<Text>();
                    rowText.font = font;
                    rowText.fontSize = 10;
                    var isTop = filteredState.HighestPriorityFilteredItem?.CycleId == item.CycleId;
                    rowText.text = (isTop ? "★ " : "") + $"{item.Title} [{item.PriorityScore}] {item.RiskLevelLabel}";
                    if (isTop) rowText.fontStyle = FontStyle.Bold;
                    row.GetComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                }
            }
        }

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