using System.Collections.Generic;
using System.Linq;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Enums;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Gere o micro-roteiro narrativo contextual de um hotspot: construir passos a partir da proposta,
    /// navegar entre passos, abrir/fechar narrativa. Integra com QuestHotspotContextState e com o contexto do hotspot.
    /// </summary>
    public class QuestHotspotStoryController : UnityEngine.MonoBehaviour
    {
        private QuestPresentationSession _session;

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

        /// <summary>Constrói os passos do micro-roteiro para o hotspot e atribui ao contexto actual. Não activa a narrativa.</summary>
        public void BuildAndAssignStorySteps(ProposalVisualHotspot hotspot)
        {
            if (_session?.CurrentHotspotContext == null || hotspot == null) return;

            var steps = BuildStorySteps(hotspot);
            _session.CurrentHotspotContext.StorySteps = steps;
            _session.CurrentHotspotContext.CurrentStoryStepIndex = -1;
            _session.CurrentHotspotContext.IsStoryActive = false;
        }

        /// <summary>Activa a narrativa contextual (primeiro passo). Só tem efeito se o contexto tiver passos.</summary>
        public void StartStory()
        {
            var ctx = _session?.CurrentHotspotContext;
            if (ctx == null || !ctx.IsContextOpen || ctx.StorySteps == null || ctx.StorySteps.Count == 0) return;
            ctx.IsStoryActive = true;
            ctx.CurrentStoryStepIndex = 0;
        }

        /// <summary>Avança para o próximo passo do micro-roteiro (se activo).</summary>
        public void NextStep()
        {
            var ctx = _session?.CurrentHotspotContext;
            if (ctx == null || !ctx.IsStoryActive || ctx.StorySteps == null || ctx.StorySteps.Count == 0) return;
            if (ctx.CurrentStoryStepIndex < ctx.StorySteps.Count - 1)
                ctx.CurrentStoryStepIndex++;
        }

        /// <summary>Volta ao passo anterior do micro-roteiro (se activo).</summary>
        public void PreviousStep()
        {
            var ctx = _session?.CurrentHotspotContext;
            if (ctx == null || !ctx.IsStoryActive || ctx.StorySteps == null || ctx.StorySteps.Count == 0) return;
            if (ctx.CurrentStoryStepIndex > 0)
                ctx.CurrentStoryStepIndex--;
        }

        /// <summary>Fecha a narrativa contextual (volta à vista simples do hotspot).</summary>
        public void CloseStory()
        {
            var ctx = _session?.CurrentHotspotContext;
            if (ctx == null) return;
            ctx.IsStoryActive = false;
            ctx.CurrentStoryStepIndex = -1;
        }

        private List<QuestHotspotStoryStep> BuildStorySteps(ProposalVisualHotspot hotspot)
        {
            var steps = new List<QuestHotspotStoryStep>();
            var order = 0;

            ProposalGuidedTourStep relatedStep = null;
            if (!string.IsNullOrEmpty(hotspot.RelatedGuidedTourStepId) && _session.GuidedSteps != null)
                relatedStep = _session.GuidedSteps.FirstOrDefault(s => s.Id == hotspot.RelatedGuidedTourStepId);

            ProposalSceneState relatedState = null;
            if (_session.SceneStates != null && _session.SceneStates.Count > 0)
            {
                var withHotspot = _session.SceneStates.FirstOrDefault(s =>
                    s.PrimaryHotspotIds != null && s.PrimaryHotspotIds.Contains(hotspot.Id));
                if (withHotspot != null) relatedState = withHotspot;
            }

            // Passo 0: visão geral do hotspot
            steps.Add(new QuestHotspotStoryStep
            {
                Id = hotspot.Id + "_step0",
                HotspotId = hotspot.Id,
                Title = hotspot.Title ?? "Ponto de destaque",
                Summary = string.IsNullOrEmpty(hotspot.Description) ? "Foco comercial neste elemento." : hotspot.Description.Trim(),
                SalesMessage = hotspot.IsPremiumUpsell ? "Oportunidade de valor acrescido." : (hotspot.SalesValueScore > 0 ? "Elemento-chave para o impacto comercial." : "Reforce a narrativa de venda neste ponto."),
                StepOrder = order++,
                IsUpsellMoment = hotspot.IsPremiumUpsell,
                RelatedGuidedStepId = relatedStep?.Id,
                RelatedSceneStateId = relatedState?.Id,
                SuggestedFocusSeconds = hotspot.SuggestedFocusDurationMinutes > 0 ? hotspot.SuggestedFocusDurationMinutes * 60 : 0
            });

            // Passo opcional: mensagem do passo guiado relacionado
            if (relatedStep != null)
            {
                steps.Add(new QuestHotspotStoryStep
                {
                    Id = hotspot.Id + "_step_guided",
                    HotspotId = hotspot.Id,
                    Title = relatedStep.Title ?? "Passo guiado",
                    Summary = string.IsNullOrEmpty(relatedStep.Description) ? "" : relatedStep.Description.Trim(),
                    SalesMessage = string.IsNullOrEmpty(relatedStep.SalesMessage) ? "Mensagem do roteiro principal." : relatedStep.SalesMessage.Trim(),
                    StepOrder = order++,
                    IsUpsellMoment = relatedStep.FocusType == ProposalGuidedTourFocusType.PremiumUpsell,
                    RelatedGuidedStepId = relatedStep.Id,
                    RelatedSceneStateId = relatedState?.Id,
                    SuggestedFocusSeconds = relatedStep.SuggestedDurationMinutes > 0 ? relatedStep.SuggestedDurationMinutes * 60 : 0
                });
            }

            // Passo opcional: estado da cena
            if (relatedState != null)
            {
                steps.Add(new QuestHotspotStoryStep
                {
                    Id = hotspot.Id + "_step_scene",
                    HotspotId = hotspot.Id,
                    Title = relatedState.Name ?? "Momento na jornada",
                    Summary = string.IsNullOrEmpty(relatedState.Description) ? "" : relatedState.Description.Trim(),
                    SalesMessage = string.IsNullOrEmpty(relatedState.TransitionFromPreviousSummary) ? "Contexto visual deste momento." : relatedState.TransitionFromPreviousSummary,
                    StepOrder = order++,
                    IsUpsellMoment = false,
                    RelatedSceneStateId = relatedState.Id,
                    SuggestedFocusSeconds = 0
                });
            }

            // Passo opcional: fechamento / decisão (quando há DecisionSummary e é hotspot premium)
            if (hotspot.IsPremiumUpsell && _session.DecisionSummary != null && !string.IsNullOrEmpty(_session.DecisionSummary.FinalSalesMessage))
            {
                steps.Add(new QuestHotspotStoryStep
                {
                    Id = hotspot.Id + "_step_close",
                    HotspotId = hotspot.Id,
                    Title = "Fechamento",
                    Summary = _session.DecisionSummary.ExecutiveShortSummary ?? "",
                    SalesMessage = _session.DecisionSummary.FinalSalesMessage,
                    StepOrder = order++,
                    IsUpsellMoment = true,
                    SuggestedFocusSeconds = 0
                });
            }

            return steps;
        }
    }
}
