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 pacotes comerciais disponíveis (tier, faixa orçamento, upsell/downsell) e permite aplicar à proposta ativa.
    /// </summary>
    public class CommercialPackageView : MonoBehaviour
    {
        private const string Title = "Pacotes Comerciais / Upgrade de Proposta";
        private const string NenhumProjeto = "Nenhum projeto ou proposta ativa.";
        private const string PacoteAtual = "Pacote atual: ";
        private const string NenhumPacote = "Nenhum pacote aplicado.";
        private const string OrcamentoAlvo = "Orçamento-alvo: ";
        private const string Aplicar = "Aplicar";

        private AppSession _session;
        private ICommercialPackageService _packageService;
        private Transform _contentRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _packageService = ServiceRegistry.Instance.Get<ICommercialPackageService>();
            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 = 280;
            var vlg = _contentRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            vlg.spacing = 6;
            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 current = string.IsNullOrEmpty(active.SelectedCommercialPackageId)
                ? null
                : _packageService?.GetById(active.SelectedCommercialPackageId);
            AppendText(_contentRoot, PacoteAtual + (current != null ? current.Name + " (" + TierText(current.Tier) + ")" : NenhumPacote));

            var packages = _packageService?.GetAvailableForProject(project) ?? new List<ProposalCommercialPackage>();
            if (packages.Count == 0)
            {
                AppendText(_contentRoot, "Nenhum pacote disponível para o template atual.");
                return;
            }

            foreach (var pkg in packages)
            {
                var card = new GameObject("PackageCard");
                card.transform.SetParent(_contentRoot, false);
                card.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 72);
                var cardVlg = card.AddComponent<VerticalLayoutGroup>();
                cardVlg.spacing = 2;
                cardVlg.padding = new RectOffset(8, 8, 8, 8);
                cardVlg.childForceExpandHeight = false;
                cardVlg.childForceExpandWidth = true;
                card.AddComponent<Image>().color = new Color(0.97f, 0.96f, 0.94f, 1f);

                var nameLine = new GameObject("Name");
                nameLine.transform.SetParent(card.transform, false);
                nameLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 16);
                var nameText = nameLine.AddComponent<Text>();
                nameText.text = pkg.Name + " — " + TierText(pkg.Tier);
                nameText.font = _font;
                nameText.fontSize = 13;
                nameText.fontStyle = FontStyle.Bold;

                var budgetLine = new GameObject("Budget");
                budgetLine.transform.SetParent(card.transform, false);
                budgetLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                var budgetText = budgetLine.AddComponent<Text>();
                budgetText.text = OrcamentoAlvo + "R$ " + pkg.TargetBudgetRangeMin.ToString("N0") + " – R$ " + pkg.TargetBudgetRangeMax.ToString("N0");
                budgetText.font = _font;
                budgetText.fontSize = 11;

                if (!string.IsNullOrEmpty(pkg.UpsellNotes) || !string.IsNullOrEmpty(pkg.DownsellNotes))
                {
                    var notesLine = new GameObject("Notes");
                    notesLine.transform.SetParent(card.transform, false);
                    notesLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 12);
                    var notesText = notesLine.AddComponent<Text>();
                    notesText.text = (!string.IsNullOrEmpty(pkg.UpsellNotes) ? "Upsell: " + pkg.UpsellNotes : "") + (!string.IsNullOrEmpty(pkg.DownsellNotes) ? " Downsell: " + pkg.DownsellNotes : "");
                    notesText.font = _font;
                    notesText.fontSize = 10;
                    notesText.color = new Color(0.4f, 0.4f, 0.45f, 1f);
                }

                var row = new GameObject("ButtonRow");
                row.transform.SetParent(card.transform, false);
                row.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 24);
                var rowHlg = row.AddComponent<HorizontalLayoutGroup>();
                rowHlg.spacing = 8;
                rowHlg.childForceExpandWidth = false;
                CreateButton(row.transform, Aplicar, () => _session?.ApplyCommercialPackage(pkg.Id));
            }
        }

        private static string TierText(CommercialPackageTier tier)
        {
            switch (tier)
            {
                case CommercialPackageTier.Essential: return "Essential";
                case CommercialPackageTier.Standard: return "Standard";
                case CommercialPackageTier.Premium: return "Premium";
                case CommercialPackageTier.Luxury: return "Luxury";
                default: return "—";
            }
        }

        private void CreateButton(Transform parent, string label, System.Action onClick)
        {
            var go = new GameObject("Btn");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(80, 22);
            go.AddComponent<LayoutElement>().preferredWidth = 80;
            go.AddComponent<LayoutElement>().preferredHeight = 22;
            var btn = go.AddComponent<Button>();
            go.AddComponent<Image>().color = new Color(0.35f, 0.55f, 0.4f, 1f);
            var textGo = new GameObject("Text");
            textGo.transform.SetParent(go.transform, false);
            var rt = textGo.AddComponent<RectTransform>();
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.offsetMin = Vector2.zero;
            rt.offsetMax = Vector2.zero;
            var t = textGo.AddComponent<Text>();
            t.text = label;
            t.font = _font;
            t.fontSize = 11;
            t.alignment = TextAnchor.MiddleCenter;
            t.color = Color.white;
            btn.onClick.AddListener(() => onClick?.Invoke());
        }

        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 static void ClearChildren(Transform root)
        {
            if (root == null) return;
            for (var i = root.childCount - 1; i >= 0; i--)
                Object.Destroy(root.GetChild(i).gameObject);
        }
    }
}
