using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Enums;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe resumo comercial / orçamento estimado da proposta atual.
    /// Atualiza automaticamente quando a proposta ou os itens do showroom mudam.
    /// </summary>
    public class ProposalSummaryView : MonoBehaviour
    {
        private const string Title = "Resumo Comercial / Orçamento Estimado";
        private const string NenhumProjeto = "Nenhum projeto iniciado.";
        private const string Itens = "Itens na proposta: ";
        private const string Total = "Valor total estimado: ";
        private const string Fornecedores = "Fornecedores envolvidos: ";
        private const string StatusLabel = "Status: ";
        private const string DraftText = "Rascunho";
        private const string ReadyText = "Pronta";

        private AppSession _session;
        private IProposalPricingService _pricingService;
        private Text _contentText;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _pricingService = ServiceRegistry.Instance.Get<IProposalPricingService>();
            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 = 6;
                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, 100);
            var contentLE = contentGo.AddComponent<LayoutElement>();
            contentLE.preferredHeight = 100;
            _contentText = contentGo.AddComponent<Text>();
            _contentText.font = font;
            _contentText.fontSize = 15;
            _contentText.alignment = TextAnchor.UpperLeft;
        }

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

            var project = _session?.CurrentProject;
            if (project == null)
            {
                _contentText.text = NenhumProjeto;
                return;
            }

            var summary = _pricingService?.GetPricingSummary(project) ?? new ProposalPricingSummary();
            var statusStr = project.Status == EventProjectStatus.Draft ? DraftText : ReadyText;
            var culture = new CultureInfo("pt-BR");
            var totalStr = summary.TotalEstimated.ToString("C2", culture);

            _contentText.text = $"{Itens}{summary.ItemCount}\n" +
                                $"{Total}{totalStr}\n" +
                                $"{Fornecedores}{summary.SupplierCount}\n" +
                                $"{StatusLabel}{statusStr}";
        }
    }
}
