using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe avaliação de cronograma operacional e sequência de montagem (tempo total, prontidão, passos críticos, dependências, avisos e recomendações).
    /// </summary>
    public class EventSetupTimelineView : MonoBehaviour
    {
        private const string Title = "Cronograma / Montagem do Evento";
        private const string NenhumProjeto = "Nenhum projeto ou proposta ativa.";
        private const string TempoTotal = "Tempo total estimado de montagem: ";
        private const string Prontidao = "Prontidão para execução: ";
        private const string PassosCriticos = "Passos críticos";
        private const string Dependencias = "Problemas de dependência";
        private const string Avisos = "Avisos de montagem";
        private const string Recomendacoes = "Recomendações";

        private AppSession _session;
        private IEventSetupTimelineService _timelineService;
        private Transform _contentRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _timelineService = ServiceRegistry.Instance.Get<IEventSetupTimelineService>();
            if (_session != null)
                _session.OnSessionChanged += UpdateContent;

            _font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            BuildUI();
            UpdateContent();
        }

        private void OnDestroy()
        {
            if (_session != null)
                _session.OnSessionChanged -= UpdateContent;
        }

        private void BuildUI()
        {
            var layout = gameObject.GetComponent<VerticalLayoutGroup>();
            if (layout == null)
            {
                layout = gameObject.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 6;
                layout.padding = new RectOffset(12, 12, 12, 12);
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;
            }

            var titleGo = new GameObject("Title");
            titleGo.transform.SetParent(transform, false);
            titleGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var titleText = titleGo.AddComponent<Text>();
            titleText.text = Title;
            titleText.font = _font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            _contentRoot = new GameObject("ContentRoot").transform;
            _contentRoot.SetParent(transform, false);
            _contentRoot.gameObject.AddComponent<LayoutElement>().preferredHeight = 200;
            var vlg = _contentRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            vlg.spacing = 4;
            vlg.childForceExpandHeight = false;
            vlg.childForceExpandWidth = true;
        }

        private void UpdateContent()
        {
            ClearChildren(_contentRoot);

            var project = _session?.CurrentProject;
            var active = project?.GetActiveProposal();
            if (project == null || active == null)
            {
                AppendText(_contentRoot, NenhumProjeto);
                return;
            }

            var timeline = _timelineService?.Evaluate(project, active);
            if (timeline == null)
            {
                AppendText(_contentRoot, "Avaliação de cronograma não disponível.");
                return;
            }

            var minutes = timeline.EstimatedTotalSetupMinutes;
            var hours = minutes / 60;
            var mins = minutes % 60;
            var timeStr = hours > 0 ? hours + "h" + (mins > 0 ? " " + mins + " min" : "") : minutes + " min";
            AppendText(_contentRoot, TempoTotal + timeStr);
            AppendText(_contentRoot, Prontidao + ReadinessStatusText(timeline.ExecutionReadinessStatus));
            AppendList(_contentRoot, PassosCriticos, timeline.CriticalSteps, new Color(0.4f, 0.3f, 0.5f, 1f));
            AppendList(_contentRoot, Dependencias, timeline.DependencyIssues, new Color(0.6f, 0.25f, 0.2f, 1f));
            AppendList(_contentRoot, Avisos, timeline.SetupWarnings, new Color(0.6f, 0.4f, 0.15f, 1f));
            AppendList(_contentRoot, Recomendacoes, timeline.Recommendations, new Color(0.2f, 0.4f, 0.5f, 1f));
        }

        private static string ReadinessStatusText(ExecutionReadinessStatus s)
        {
            switch (s)
            {
                case ExecutionReadinessStatus.Ready: return "Pronta";
                case ExecutionReadinessStatus.Warning: return "Atenção";
                case ExecutionReadinessStatus.NotReady: return "Não pronta";
                default: return "—";
            }
        }

        private void AppendText(Transform parent, string text)
        {
            var go = new GameObject("TextLine");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
            var t = go.AddComponent<Text>();
            t.text = text;
            t.font = _font;
            t.fontSize = 12;
        }

        private void AppendList(Transform parent, string title, List<string> items, Color color)
        {
            if (items == null || items.Count == 0) return;
            var labelGo = new GameObject("Label");
            labelGo.transform.SetParent(parent, false);
            labelGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
            var label = labelGo.AddComponent<Text>();
            label.text = title + ":";
            label.font = _font;
            label.fontSize = 11;
            label.fontStyle = FontStyle.Bold;
            foreach (var item in items)
            {
                var line = new GameObject("Item");
                line.transform.SetParent(parent, false);
                line.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                var t = line.AddComponent<Text>();
                t.text = "• " + item;
                t.font = _font;
                t.fontSize = 11;
                t.color = color;
            }
        }

        private static void ClearChildren(Transform root)
        {
            if (root == null) return;
            for (var i = root.childCount - 1; i >= 0; i--)
                Object.Destroy(root.GetChild(i).gameObject);
        }
    }
}
