using System;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;
using EventsAppQuest.Web.Core;
using EventsAppQuest.Web.Domain;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Painel mock: "Aplicar resultado da sessão Quest à oportunidade". Cria um snapshot mock e aplica via IMockWebDataService.
    /// Não depende do runtime Quest; apenas simula a ponte.
    /// </summary>
    public class ApplyQuestResultPanel : MonoBehaviour, IWebContentRoot
    {
        private Transform _content;
        private Text _resultText;

        public void SetContentRoot(Transform contentRoot) => _content = contentRoot;

        private void Start()
        {
            BuildUI();
        }

        private void BuildUI()
        {
            if (_content == null) return;
            var service = WebRuntimeContext.DataService;
            if (service == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");

            var opps = service.GetOpportunities();
            foreach (var opp in opps)
            {
                var oppId = opp.Id;
                var btnGo = new GameObject("Apply_" + oppId);
                btnGo.transform.SetParent(_content, false);
                var btnRt = btnGo.AddComponent<RectTransform>();
                btnRt.sizeDelta = new Vector2(0, 26);
                var btnImage = btnGo.AddComponent<Image>();
                btnImage.color = new Color(0.35f, 0.65f, 0.9f, 1f);
                var btn = btnGo.AddComponent<Button>();
                var btnTextGo = new GameObject("Text");
                btnTextGo.transform.SetParent(btnGo.transform, false);
                var btnText = btnTextGo.AddComponent<Text>();
                btnText.text = "[Aplicar resultado Quest] " + opp.Title;
                btnText.font = font;
                btnText.fontSize = 11;
                btnText.alignment = TextAnchor.MiddleLeft;
                var btnTextRt = btnTextGo.GetComponent<RectTransform>();
                btnTextRt.anchorMin = Vector2.zero;
                btnTextRt.anchorMax = Vector2.one;
                btnTextRt.offsetMin = new Vector2(4, 0);
                btnTextRt.offsetMax = Vector2.zero;
                btn.targetGraphic = btnImage;
                btn.onClick.AddListener(() => OnApplyClicked(oppId));
            }

            var resultGo = new GameObject("ResultText");
            resultGo.transform.SetParent(_content, false);
            var resultRt = resultGo.AddComponent<RectTransform>();
            resultRt.sizeDelta = new Vector2(0, 32);
            _resultText = resultGo.AddComponent<Text>();
            _resultText.font = font;
            _resultText.fontSize = 11;
            _resultText.text = "Clique num botão para aplicar resultado mock da sessão Quest à oportunidade.";
        }

        private void OnApplyClicked(string oppId)
        {
            var service = WebRuntimeContext.DataService as MockWebDataService;
            if (service == null) return;

            var snapshot = CreateMockSnapshot();
            var (sessionRecordId, indicators) = service.ApplyQuestSessionToOpportunity(snapshot, oppId);
            WebRuntimeContext.NotifyDataChanged();
            _resultText.text = sessionRecordId != null
                ? "Aplicado. SessionRecord: " + sessionRecordId + ". Indicadores: " + string.Join(", ", indicators)
                : "Erro ao aplicar.";
        }

        private static QuestSessionSnapshot CreateMockSnapshot()
        {
            return new QuestSessionSnapshot
            {
                SessionId = "quest-mock-" + Guid.NewGuid().ToString("N").Substring(0, 6),
                ProjectId = "proj-1",
                RecommendedProposalId = "prop-guid-1",
                SelectedProposalId = "prop-guid-1",
                FinalDecisionState = WebSessionDecisionState.ReadyToClose,
                ConfirmedCTA = "Fechar contrato",
                SuggestedNextAction = "Enviar minuta e agendar assinatura",
                FollowUpPriority = FollowUpPriority.High,
                OutcomeSummary = "Cliente demonstrou alta intenção na sessão Quest.",
                ClosingSummary = "Fechamento positivo.",
                ConfidenceLevel = "Alta",
                EngagementLabel = "High",
                QualityLabel = "High",
                HasExportPayload = true,
                HasHandoffReport = true,
                HasShareableSummary = true,
                HasQualityAssessment = true,
                HasImprovementPlan = false,
                Timestamp = DateTime.UtcNow
            };
        }
    }
}
