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

namespace EventsAppQuest.Infrastructure.Services
{
    /// <summary>
    /// Gera o plano de apresentação MR a partir de roteiro guiado, hotspots, estados de cena, recomendação, resumo executivo, momentos e transições.
    /// </summary>
    public class MockMRPresentationPlanningService : IMRPresentationPlanningService
    {
        public ProposalMRPresentationPlan GeneratePlan(EventProject project, EventProjectProposal proposal)
        {
            var plan = new ProposalMRPresentationPlan();
            if (proposal == null) return plan;

            plan.ProposalId = proposal.Id;
            plan.PresentationTitle = (proposal.Name ?? "Proposta") + " — Apresentação Quest";

            var guidedSteps = proposal.GuidedTourSteps ?? new List<ProposalGuidedTourStep>();
            var hotspots = proposal.VisualHotspots ?? new List<ProposalVisualHotspot>();
            var sceneStates = proposal.SceneStates ?? new List<ProposalSceneState>();
            var momentPlans = proposal.MomentPlans ?? new List<ProposalMomentPlan>();

            plan.GuidedSequenceStepIds = guidedSteps.OrderBy(s => s.DisplayOrder).Select(s => s.Id).Where(id => !string.IsNullOrEmpty(id)).ToList();
            plan.HotspotIds = hotspots.OrderBy(h => h.HighlightPriority).Select(h => h.Id).Where(id => !string.IsNullOrEmpty(id)).ToList();
            plan.SceneStateIds = sceneStates.OrderBy(s => s.DisplayOrder).Select(s => s.Id).Where(id => !string.IsNullOrEmpty(id)).ToList();

            var zoneSet = new HashSet<string>();
            foreach (var s in guidedSteps)
                if (s.RelatedZoneTypes != null)
                    foreach (var z in s.RelatedZoneTypes)
                        if (!string.IsNullOrEmpty(z)) zoneSet.Add(z);
            foreach (var h in hotspots)
                if (h.RelatedZoneTypes != null)
                    foreach (var z in h.RelatedZoneTypes)
                        if (!string.IsNullOrEmpty(z)) zoneSet.Add(z);
            foreach (var st in sceneStates)
                if (st.ActiveZoneTypes != null)
                    foreach (var z in st.ActiveZoneTypes)
                        if (!string.IsNullOrEmpty(z)) zoneSet.Add(z);
            plan.PriorityZones = zoneSet.OrderBy(z => z).ToList();

            plan.KeySellingMoments = new List<string>();
            foreach (var s in guidedSteps.Where(s => s.IsKeyMoment && !string.IsNullOrEmpty(s.Title)))
                plan.KeySellingMoments.Add(s.Title);
            foreach (var h in hotspots.Take(3).Where(h => !string.IsNullOrEmpty(h.Title) && !plan.KeySellingMoments.Contains(h.Title)))
                plan.KeySellingMoments.Add(h.Title);

            var totalMinutes = guidedSteps.Sum(s => s.SuggestedDurationMinutes > 0 ? s.SuggestedDurationMinutes : 3);
            plan.RecommendedSessionDurationMinutes = totalMinutes > 0 ? totalMinutes : 15;

            var isRecommended = project != null && project.LastRecommendationSummary?.RecommendedProposalId == proposal.Id;
            var decision = project?.LastDecisionSummary;
            var rec = project?.LastRecommendationSummary;

            if (decision != null && decision.RecommendedProposalId == proposal.Id && decision.DecisionReadinessLevel == ProposalDecisionReadinessLevel.ReadyToClose)
            {
                plan.TargetExperienceMode = MRPresentationTargetMode.ExecutiveClosingMode;
                plan.ExecutivePresentationGoal = decision.SuggestedNextAction ?? "Conduzir ao fechamento da proposta.";
            }
            else if (guidedSteps.Count >= 3)
            {
                plan.TargetExperienceMode = MRPresentationTargetMode.GuidedSalesTour;
                plan.ExecutivePresentationGoal = rec?.SuggestedSalesAngle ?? "Apresentar valor da proposta de forma guiada.";
            }
            else if (hotspots.Count >= 3 && sceneStates.Count >= 2)
            {
                plan.TargetExperienceMode = MRPresentationTargetMode.FreeExploration;
                plan.ExecutivePresentationGoal = "Exploração dos destaques e evolução visual da proposta.";
            }
            else
            {
                plan.TargetExperienceMode = MRPresentationTargetMode.GuidedSalesTour;
                plan.ExecutivePresentationGoal = "Apresentar proposta ao cliente no Quest.";
            }

            var review = proposal.ReviewSummary ?? (project?.GetActiveProposal()?.Id == proposal.Id ? project.LastProposalReviewSummary : null);
            plan.ReadyForMRMapping = (plan.GuidedSequenceStepIds.Count > 0 || plan.HotspotIds.Count > 0)
                && (review?.IsReadyForPresentation == true || (guidedSteps.Count + hotspots.Count + sceneStates.Count) >= 2);

            return plan;
        }
    }
}
