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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe detalhes do projeto atual em memoria: nome, categoria, espaco, template,
    /// fornecedores selecionados e status. Inclui acao para marcar proposta como pronta.
    /// </summary>
    public class ProjectDetailsView : MonoBehaviour
    {
        private const string Title = "Detalhes do Projeto Atual";
        private const string NenhumProjeto = "Nenhum projeto iniciado.";
        private const string Nome = "Nome: ";
        private const string Categoria = "Categoria: ";
        private const string Espaco = "Espaço: ";
        private const string Template = "Template: ";
        private const string Fornecedores = "Fornecedores: ";
        private const string StatusLabel = "Status: ";
        private const string TemaLabel = "Tema: ";
        private const string MoodLabel = "Mood: ";
        private const string ApresentacaoLabel = "Apresentação: ";
        private const string NarrativaLabel = "Narrativa: ";
        private const string ProntaParaApresentacaoLabel = "Pronta para apresentação: ";
        private const string VersoesSalvasLabel = "Versões salvas: ";
        private const string DraftText = "Rascunho";
        private const string ReadyText = "Pronta";
        private const string ButtonMarcarPronta = "Marcar proposta como pronta";

        private AppSession _session;
        private Text _contentText;
        private Button _marcarProntaButton;

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

            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 = 8;
                layout.padding = new RectOffset(12, 12, 12, 12);
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;
            }

            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

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

            var contentGo = new GameObject("Content");
            contentGo.transform.SetParent(transform, false);
            var contentRt = contentGo.AddComponent<RectTransform>();
            contentRt.sizeDelta = new Vector2(0, 140);
            var contentLayoutElem = contentGo.AddComponent<LayoutElement>();
            contentLayoutElem.preferredHeight = 140;
            _contentText = contentGo.AddComponent<Text>();
            _contentText.font = font;
            _contentText.fontSize = 14;
            _contentText.alignment = TextAnchor.UpperLeft;

            var buttonGo = new GameObject("MarcarProntaButton");
            buttonGo.transform.SetParent(transform, false);
            var buttonRt = buttonGo.AddComponent<RectTransform>();
            buttonRt.sizeDelta = new Vector2(0, 32);
            var buttonLayoutElem = buttonGo.AddComponent<LayoutElement>();
            buttonLayoutElem.preferredHeight = 32;

            var image = buttonGo.AddComponent<Image>();
            image.color = new Color(0.25f, 0.45f, 0.7f, 1f);

            _marcarProntaButton = buttonGo.AddComponent<Button>();
            _marcarProntaButton.targetGraphic = image;
            _marcarProntaButton.onClick.AddListener(OnMarcarProntaClicked);

            var labelGo = new GameObject("Text");
            labelGo.transform.SetParent(buttonGo.transform, false);
            var labelRt = labelGo.AddComponent<RectTransform>();
            labelRt.anchorMin = Vector2.zero;
            labelRt.anchorMax = Vector2.one;
            labelRt.offsetMin = Vector2.zero;
            labelRt.offsetMax = Vector2.zero;
            var labelText = labelGo.AddComponent<Text>();
            labelText.text = ButtonMarcarPronta;
            labelText.font = font;
            labelText.fontSize = 16;
            labelText.alignment = TextAnchor.MiddleCenter;
            labelText.color = Color.white;
        }

        private void OnMarcarProntaClicked()
        {
            if (_session?.CurrentProject == null) return;
            if (_session.CurrentProject.Status != EventProjectStatus.Draft) return;

            _session.SetProjectStatus(EventProjectStatus.Ready);
        }

        private void UpdateContent()
        {
            if (_contentText == null) return;

            var project = _session?.CurrentProject;
            if (project == null)
            {
                _contentText.text = NenhumProjeto;
                if (_marcarProntaButton != null) _marcarProntaButton.gameObject.SetActive(false);
                return;
            }

            var categoryName = ResolveCategoryName(project.EventCategoryId);
            var spaceName = ResolveSpaceName(project.SpaceId);
            var templateName = ResolveTemplateName(project.EventTemplateId);
            var supplierNames = ResolveSupplierNames(project.SupplierIds);
            var statusText = project.Status == EventProjectStatus.Draft ? DraftText : ReadyText;
            var themeName = ResolveThemeName(project.SelectedThemeId);
            var moodText = ResolveMood(project.SelectedThemeId);
            var stepCount = project.GeneratedPresentationSteps?.Count ?? 0;
            var narrativaText = stepCount > 0 ? $"{stepCount} etapa(s)" : "—";
            var narrativaGerada = stepCount > 0 ? "Sim" : "Não";
            var prontaText = project.LastProposalReviewSummary != null
                ? (project.LastProposalReviewSummary.IsReadyForPresentation ? "Sim" : "Não")
                : "—";
            var versoesCount = _session != null ? (_session.SavedSnapshots?.Count ?? 0) : 0;

            _contentText.text = $"{Nome}{project.Name}\n" +
                                $"{Categoria}{categoryName}\n" +
                                $"{Espaco}{spaceName}\n" +
                                $"{Template}{templateName}\n" +
                                $"{Fornecedores}{supplierNames}\n" +
                                $"{StatusLabel}{statusText}\n" +
                                $"{TemaLabel}{themeName}\n" +
                                $"{MoodLabel}{moodText}\n" +
                                $"{ApresentacaoLabel}{narrativaText}\n" +
                                $"{NarrativaLabel}{narrativaGerada}\n" +
                                $"{ProntaParaApresentacaoLabel}{prontaText}\n" +
                                $"{VersoesSalvasLabel}{versoesCount}";

            if (_marcarProntaButton != null)
                _marcarProntaButton.gameObject.SetActive(project.Status == EventProjectStatus.Draft);
        }

        private static string ResolveCategoryName(string id)
        {
            if (string.IsNullOrEmpty(id)) return "—";
            var service = ServiceRegistry.Instance.Get<IEventCategoryService>();
            var c = service?.GetById(id);
            return c?.DisplayName ?? id;
        }

        private static string ResolveSpaceName(string id)
        {
            if (string.IsNullOrEmpty(id)) return "—";
            var service = ServiceRegistry.Instance.Get<ISpaceService>();
            var s = service?.GetById(id);
            return s?.Name ?? id;
        }

        private static string ResolveTemplateName(string id)
        {
            if (string.IsNullOrEmpty(id)) return "—";
            var service = ServiceRegistry.Instance.Get<ITemplateService>();
            var t = service?.GetById(id);
            return t?.Name ?? id;
        }

        private static string ResolveSupplierNames(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return "—";
            var service = ServiceRegistry.Instance.Get<ISupplierService>();
            if (service == null) return string.Join(", ", ids);

            var names = new List<string>();
            foreach (var id in ids)
            {
                var s = service.GetById(id);
                names.Add(s != null ? s.Name : id);
            }
            return string.Join(", ", names);
        }

        private static string ResolveThemeName(string themeId)
        {
            if (string.IsNullOrEmpty(themeId)) return "—";
            var service = ServiceRegistry.Instance.Get<IVisualThemeService>();
            var t = service?.GetById(themeId);
            return t?.Name ?? "—";
        }

        private static string ResolveMood(string themeId)
        {
            if (string.IsNullOrEmpty(themeId)) return "—";
            var service = ServiceRegistry.Instance.Get<IVisualThemeService>();
            var t = service?.GetById(themeId);
            return !string.IsNullOrEmpty(t?.Mood) ? t.Mood : "—";
        }
    }
}
