using System;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Consolida o resultado comercial da sessão Quest a partir do closing e da proposta (recomendação, decisão).
    /// Prepara dados para futura exportação/integração web ou CRM sem depender de backend real.
    /// </summary>
    public class QuestCommercialOutcomeController : UnityEngine.MonoBehaviour
    {
        private QuestPresentationSession _session;
        private static int _sessionCounter;

        /// <summary>Resultado comercial actual (pode ser null).</summary>
        public QuestCommercialOutcome Current => _session?.CurrentCommercialOutcome;

        /// <summary>Liga o controlador à sessão.</summary>
        public void Bind(QuestPresentationSession session)
        {
            _session = session;
        }

        /// <summary>Regista o resultado comercial a partir do fechamento e do CTA confirmado (PrimaryCTA ou SecondaryCTA).</summary>
        public void RecordFromClosing(string ctaConfirmed)
        {
            if (_session == null) return;
            var closing = _session.CurrentClosingState;
            var isPrimary = string.Equals(ctaConfirmed, "PrimaryCTA", StringComparison.OrdinalIgnoreCase);
            var isSecondary = string.Equals(ctaConfirmed, "SecondaryCTA", StringComparison.OrdinalIgnoreCase);

            var recommendedId = closing?.RecommendedProposalId ?? _session.DecisionSummary?.RecommendedProposalId ?? _session.RecommendationSummary?.RecommendedProposalId ?? _session.Proposal?.Id;
            var selectedId = recommendedId;
            var nextAction = closing?.SuggestedNextAction ?? _session.DecisionSummary?.SuggestedNextAction ?? "Apresentar proposta ao cliente";
            var confidence = closing?.ConfidenceLabel ?? (_session.RecommendationSummary != null && _session.RecommendationSummary.RecommendationConfidenceScore > 0
                ? "Confiança " + _session.RecommendationSummary.RecommendationConfidenceScore + "%"
                : "Média");
            var summary = closing != null
                ? (closing.ClosingHeadline + ". " + (closing.ClosingSummary ?? ""))
                : "Sessão Quest concluída. Decisão registada para follow-up.";

            QuestCommercialDecisionState state;
            int followUpPriority;
            if (isPrimary)
            {
                state = closing != null && closing.IsReadyToClose ? QuestCommercialDecisionState.ReadyToClose : QuestCommercialDecisionState.ReadyToAdvance;
                followUpPriority = state == QuestCommercialDecisionState.ReadyToClose ? 0 : 1;
            }
            else if (isSecondary)
            {
                state = QuestCommercialDecisionState.NeedsFollowUp;
                followUpPriority = 2;
            }
            else
            {
                state = QuestCommercialDecisionState.Interested;
                followUpPriority = 2;
            }

            _session.CurrentCommercialOutcome = new QuestCommercialOutcome
            {
                SessionId = "Quest_" + (++_sessionCounter) + "_" + DateTime.UtcNow.ToString("yyyyMMddHHmm"),
                RecommendedProposalId = recommendedId,
                SelectedProposalId = selectedId,
                ClosingCTAChosen = isPrimary,
                SecondaryCTAChosen = isSecondary,
                FinalDecisionState = state,
                SuggestedNextAction = nextAction,
                ConfidenceLevel = confidence,
                OutcomeSummary = summary?.Trim(),
                FollowUpPriority = followUpPriority,
                Notes = null,
                Timestamp = DateTime.UtcNow
            };
            _session.LastConfirmedCTA = ctaConfirmed;
            _session.LastDecisionState = state;
            _session.CTAConfirmationCount++;
        }

        /// <summary>Marca o estado como NeedsFollowUp e actualiza o resultado se existir.</summary>
        public void MarkNeedsFollowUp()
        {
            if (_session == null) return;
            _session.LastDecisionState = QuestCommercialDecisionState.NeedsFollowUp;
            if (_session.CurrentCommercialOutcome != null)
            {
                _session.CurrentCommercialOutcome.FinalDecisionState = QuestCommercialDecisionState.NeedsFollowUp;
                _session.CurrentCommercialOutcome.FollowUpPriority = Math.Max(2, _session.CurrentCommercialOutcome.FollowUpPriority);
            }
        }

        /// <summary>Marca o estado como ReadyToAdvance e actualiza o resultado se existir.</summary>
        public void MarkReadyToAdvance()
        {
            if (_session == null) return;
            _session.LastDecisionState = QuestCommercialDecisionState.ReadyToAdvance;
            if (_session.CurrentCommercialOutcome != null)
            {
                _session.CurrentCommercialOutcome.FinalDecisionState = QuestCommercialDecisionState.ReadyToAdvance;
                _session.CurrentCommercialOutcome.FollowUpPriority = 1;
            }
        }

        /// <summary>Confirma decisão final (ReadyToClose) e actualiza o resultado se existir.</summary>
        public void ConfirmFinalDecision()
        {
            if (_session == null) return;
            _session.LastDecisionState = QuestCommercialDecisionState.ReadyToClose;
            if (_session.CurrentCommercialOutcome != null)
            {
                _session.CurrentCommercialOutcome.FinalDecisionState = QuestCommercialDecisionState.ReadyToClose;
                _session.CurrentCommercialOutcome.FollowUpPriority = 0;
            }
        }

        /// <summary>Actualiza o resultado comercial com estado e prioridade (para uso pelo painel de resultado).</summary>
        public void UpdateOutcomeState(QuestCommercialDecisionState state, int followUpPriority)
        {
            if (_session?.CurrentCommercialOutcome == null) return;
            _session.CurrentCommercialOutcome.FinalDecisionState = state;
            _session.CurrentCommercialOutcome.FollowUpPriority = followUpPriority;
            _session.LastDecisionState = state;
        }
    }
}
