using System;
using System.Collections.Generic;
using System.Text;
using EventsAppQuest.Core;
using UnityEngine;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Consolida o resumo compartilhável da sessão Quest a partir do outcome, export, handoff e decisão.
    /// Mantém tudo em memória; pode opcionalmente copiar o texto para o clipboard.
    /// </summary>
    public class QuestSessionShareableSummaryController : MonoBehaviour
    {
        private QuestPresentationSession _session;

        public QuestSessionShareableSummary Current => _session?.CurrentShareableSummary;

        public void Bind(QuestPresentationSession session)
        {
            _session = session;
        }

        /// <summary>Gera ou regenera o resumo compartilhável a partir do estado actual da sessão.</summary>
        public void GenerateSummary()
        {
            if (_session == null) return;
            try
            {
                var handoff = _session.CurrentHandoffReport;
                var export = _session.CurrentExportPayload;
                var outcome = _session.CurrentCommercialOutcome;
                var decision = _session.DecisionSummary;
                var rec = _session.RecommendationSummary;

                var sessionId = handoff?.SessionId ?? export?.SessionId ?? outcome?.SessionId ?? ("Quest_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss"));
                var title = "Resumo da sessão Quest";
                var executive = decision?.ExecutiveShortSummary
                                ?? outcome?.OutcomeSummary
                                ?? "Resumo da sessão Quest para acompanhamento comercial.";

                var recLabel = !string.IsNullOrEmpty(handoff?.RecommendedProposalId)
                    ? handoff.RecommendedProposalId
                    : (!string.IsNullOrEmpty(export?.RecommendedProposalId) ? export.RecommendedProposalId : (_session.Proposal?.Name ?? _session.Proposal?.Id ?? "—"));

                var selLabel = !string.IsNullOrEmpty(handoff?.SelectedProposalId)
                    ? handoff.SelectedProposalId
                    : (!string.IsNullOrEmpty(export?.SelectedProposalId) ? export.SelectedProposalId : (_session.Proposal?.Name ?? _session.Proposal?.Id ?? "—"));

                var decisionLabel = handoff != null
                    ? handoff.FinalDecisionState.ToString()
                    : (_session.LastDecisionState != 0 ? _session.LastDecisionState.ToString() : "ExplorationOnly");

                var ctaLabel = !string.IsNullOrEmpty(handoff?.ConfirmedCTA)
                    ? handoff.ConfirmedCTA
                    : (!string.IsNullOrEmpty(export?.ConfirmedCTA) ? export.ConfirmedCTA : (_session.LastConfirmedCTA ?? "—"));

                var nextActionLabel = !string.IsNullOrEmpty(handoff?.SuggestedNextAction)
                    ? handoff.SuggestedNextAction
                    : (!string.IsNullOrEmpty(export?.SuggestedNextAction) ? export.SuggestedNextAction : (decision?.SuggestedNextAction ?? "Apresentar proposta ao cliente"));

                var priorityLabel = handoff != null && handoff.FollowUpPriority > 0
                    ? handoff.FollowUpPriority.ToString()
                    : (outcome != null && outcome.FollowUpPriority > 0 ? outcome.FollowUpPriority.ToString() : "—");

                var highlights = new List<string>();
                if (rec != null && !string.IsNullOrEmpty(rec.ExecutiveSummary))
                    highlights.Add(rec.ExecutiveSummary);
                if (decision != null && decision.MainDecisionReasons != null && decision.MainDecisionReasons.Count > 0)
                    highlights.AddRange(decision.MainDecisionReasons);
                if (handoff != null && handoff.KeyHotspotsVisited != null && handoff.KeyHotspotsVisited.Count > 0)
                    highlights.Add("Hotspots-chave: " + string.Join(", ", handoff.KeyHotspotsVisited));

                var risks = new List<string>();
                if (decision != null && decision.KeyRisks != null && decision.KeyRisks.Count > 0)
                    risks.AddRange(decision.KeyRisks);

                var sb = new StringBuilder();
                sb.AppendLine("Resumo da sessão Quest");
                sb.AppendLine();
                sb.AppendLine("Proposta recomendada: " + recLabel);
                sb.AppendLine("Proposta apresentada: " + selLabel);
                sb.AppendLine("Decisão: " + decisionLabel);
                sb.AppendLine("CTA confirmado: " + (ctaLabel ?? "—"));
                sb.AppendLine("Próxima ação sugerida: " + (nextActionLabel ?? "—"));
                sb.AppendLine("Prioridade de follow-up: " + priorityLabel);
                sb.AppendLine();
                sb.AppendLine("Resumo executivo:");
                sb.AppendLine(executive ?? "—");
                sb.AppendLine();
                if (highlights.Count > 0)
                {
                    sb.AppendLine("Pontos-chave:");
                    foreach (var h in highlights)
                        sb.AppendLine("- " + h);
                    sb.AppendLine();
                }
                if (risks.Count > 0)
                {
                    sb.AppendLine("Riscos / pontos de atenção:");
                    foreach (var r in risks)
                        sb.AppendLine("- " + r);
                    sb.AppendLine();
                }
                if (handoff != null && handoff.KeyComparisonsViewed != null && handoff.KeyComparisonsViewed.Count > 0)
                {
                    sb.AppendLine("Comparações relevantes:");
                    foreach (var c in handoff.KeyComparisonsViewed)
                        sb.AppendLine("- " + c);
                    sb.AppendLine();
                }
                sb.AppendLine("Gerado automaticamente a partir da apresentação Quest.");

                _session.CurrentShareableSummary = new QuestSessionShareableSummary
                {
                    SessionId = sessionId ?? "",
                    Title = title,
                    ExecutiveSummary = executive?.Trim() ?? "",
                    RecommendedProposalLabel = recLabel ?? "",
                    SelectedProposalLabel = selLabel ?? "",
                    FinalDecisionLabel = decisionLabel ?? "",
                    ConfirmedCTALabel = ctaLabel ?? "",
                    SuggestedNextActionLabel = nextActionLabel ?? "",
                    FollowUpPriorityLabel = priorityLabel ?? "",
                    KeyHighlights = highlights,
                    KeyRisks = risks,
                    ShareableText = sb.ToString(),
                    GeneratedAt = DateTime.UtcNow
                };
                _session.LastShareableSummaryGeneratedAt = _session.CurrentShareableSummary.GeneratedAt;
                _session.HasShareableSummary = true;
            }
            catch (Exception)
            {
                // Fallback: não quebrar a apresentação; resumo fica null ou anterior
            }
        }

        /// <summary>Limpa o resumo actual e metadados associados.</summary>
        public void ClearSummary()
        {
            if (_session == null) return;
            _session.CurrentShareableSummary = null;
            _session.LastShareableSummaryGeneratedAt = null;
            _session.HasShareableSummary = false;
        }

        /// <summary>Tenta copiar o texto compartilhável para o clipboard, se disponível.</summary>
        public void CopyToClipboard()
        {
            if (_session?.CurrentShareableSummary == null) return;
            try
            {
                GUIUtility.systemCopyBuffer = _session.CurrentShareableSummary.ShareableText ?? "";
            }
            catch (Exception)
            {
                // Em algumas plataformas o clipboard pode não estar disponível; fallback é não fazer nada.
            }
        }
    }
}

