using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Controlador do dashboard CRM do hotel/espaço: pipeline comercial, indicadores, Leads, Oportunidades, Propostas, Sessões Quest, Follow-ups.
    /// Camada Web isolada; não altera Quest nem AppSession.
    /// </summary>
    public class HotelCRMDashboardController : MonoBehaviour
    {
        private const string WebTitle = "CRM Hotel / Espaço — Pipeline e Sessões Quest";
        private const int CanvasWidth = 1920;
        private const int CanvasHeight = 1080;

        private void Awake()
        {
            var config = WebInstallController.GetConfig();
            var seedDemo = config == null || config.SeedDemoData;
            WebRuntimeContext.DataService = new MockWebDataService(seedDemo);
            WebRuntimeContext.IndicatorsService = new CRMIndicatorsService();
        }

        private void Start()
        {
            var canvas = CreateCanvas();
            var scrollRoot = CreateScrollRoot(canvas.transform);
            var root = CreateRootWithLayout(scrollRoot);
            CreateTitle(root);
            CreateWebSection<CRMMetricsStripView>("Indicadores", root, "MetricsSection", 50);
            CreateWebSection<EventCycleDashboardStripView>("Resumo do ciclo (dashboard)", root, "CycleDashboardStripSection", 36);
            CreateWebSection<EventCycleAlertsStripView>("Alertas do ciclo (resumo)", root, "CycleAlertsStripSection", 28);
            CreateWebSection<EventCycleDashboardPanel>("Dashboard consolidado do ciclo completo", root, "EventCycleDashboardSection", 380);
            CreateWebSection<EventCycleAlertsPanel>("Alertas e pendências críticas", root, "EventCycleAlertsSection", 300);
            CreateWebSection<EventCycleActionPlanStripView>("Próximos passos (resumo)", root, "ActionPlanStripSection", 28);
            CreateWebSection<EventCycleActionPlanPanel>("Ações recomendadas (comercial e operação)", root, "EventCycleActionPlanSection", 320);
            CreateWebSection<EventCycleExecutiveSummaryStripView>("Resumo executivo (resumo)", root, "EventCycleExecutiveSummaryStripSection", 28);
            CreateWebSection<EventCycleExecutiveSummaryPanel>("Resumo executivo do ciclo completo", root, "EventCycleExecutiveSummarySection", 380);
            CreateWebSection<EventCycleClosureStripView>("Encerramento do ciclo (resumo)", root, "EventCycleClosureStripSection", 28);
            CreateWebSection<EventCycleClosurePanel>("Painel final de encerramento do ciclo", root, "EventCycleClosureSection", 320);
            CreateWebSection<EventCycleMetricsStripView>("Métricas do ciclo (resumo)", root, "EventCycleMetricsStripSection", 28);
            CreateWebSection<EventCycleMetricsPanel>("Métricas consolidadas do ciclo (performance)", root, "EventCycleMetricsSection", 320);
            CreateWebSection<EventCycleBenchmarkStripView>("Benchmark do ciclo (resumo)", root, "EventCycleBenchmarkStripSection", 28);
            CreateWebSection<EventCycleBenchmarkPanel>("Benchmark interno e comparação entre ciclos", root, "EventCycleBenchmarkSection", 360);
            CreateWebSection<EventCycleSLAStripView>("SLA do ciclo (resumo)", root, "EventCycleSLAStripSection", 28);
            CreateWebSection<EventCycleSLAPanel>("SLA e tempo entre marcos críticos", root, "EventCycleSLASection", 320);
            CreateWebSection<EventCycleDependencyMapStripView>("Mapa de dependências (resumo)", root, "EventCycleDependencyMapStripSection", 28);
            CreateWebSection<EventCycleDependencyMapPanel>("Mapa de dependências do ciclo (causa → efeito)", root, "EventCycleDependencyMapSection", 360);
            CreateWebSection<EventCycleBottleneckStripView>("Gargalos do ciclo (resumo)", root, "EventCycleBottleneckStripSection", 28);
            CreateWebSection<EventCycleBottleneckPanel>("Gargalos e priorização de destravamento", root, "EventCycleBottleneckSection", 380);
            CreateWebSection<EventCycleRecoveryPlanStripView>("Plano de recuperação (resumo)", root, "EventCycleRecoveryPlanStripSection", 28);
            CreateWebSection<EventCycleRecoveryPlanPanel>("Plano de recuperação do ciclo e estratégia sugerida", root, "EventCycleRecoveryPlanSection", 380);
            CreateWebSection<EventCycleScenarioSimulationStripView>("Simulação de cenários (resumo)", root, "EventCycleScenarioSimulationStripSection", 28);
            CreateWebSection<EventCycleScenarioSimulationPanel>("Simulação de cenários do ciclo e impacto previsto", root, "EventCycleScenarioSimulationSection", 380);
            CreateWebSection<EventCyclePortfolioPriorityStripView>("Priorização entre ciclos (resumo)", root, "EventCyclePortfolioPriorityStripSection", 28);
            CreateWebSection<EventCyclePortfolioPriorityPanel>("Fila gerencial de atenção e priorização executiva", root, "EventCyclePortfolioPrioritySection", 380);
            CreateWebSection<EventCyclePortfolioOverviewStripView>("Visão resumida da carteira (resumo)", root, "EventCyclePortfolioOverviewStripSection", 28);
            CreateWebSection<EventCyclePortfolioOverviewPanel>("Visão resumida da carteira por status, risco e prioridade", root, "EventCyclePortfolioOverviewSection", 380);
            CreateWebSection<EventCyclePortfolioFilterStripView>("Filtros da carteira (resumo)", root, "EventCyclePortfolioFilterStripSection", 28);
            CreateWebSection<EventCyclePortfolioFilterPanel>("Filtros executivos e recortes da carteira", root, "EventCyclePortfolioFilterSection", 380);
            CreateWebSection<EventCycleWatchlistStripView>("Watchlist (resumo)", root, "EventCycleWatchlistStripSection", 28);
            CreateWebSection<EventCycleWatchlistPanel>("Favoritos e casos observados (watchlist)", root, "EventCycleWatchlistSection", 380);
            CreateWebSection<EventCycleManagerNotesStripView>("Notas gerenciais (resumo)", root, "EventCycleManagerNotesStripSection", 28);
            CreateWebSection<EventCycleManagerNotesPanel>("Anotações gerenciais por caso (contexto executivo)", root, "EventCycleManagerNotesSection", 380);
            CreateWebSection<EventCycleExecutiveSnapshotsStripView>("Snapshots executivos (resumo)", root, "EventCycleExecutiveSnapshotsStripSection", 28);
            CreateWebSection<EventCycleExecutiveSnapshotsPanel>("Snapshots executivos do caso (checkpoints)", root, "EventCycleExecutiveSnapshotsSection", 420);
            CreateWebSection<EventCycleSnapshotComparisonStripView>("Evolução do caso (resumo)", root, "EventCycleSnapshotComparisonStripSection", 28);
            CreateWebSection<EventCycleSnapshotComparisonPanel>("Comparação de snapshots e leitura de evolução", root, "EventCycleSnapshotComparisonSection", 420);
            CreateWebSection<EventCycleExecutiveDecisionTrailStripView>("Trilha de decisões executivas (resumo)", root, "EventCycleExecutiveDecisionTrailStripSection", 28);
            CreateWebSection<EventCycleExecutiveDecisionTrailPanel>("Trilha gerencial do caso e histórico de decisões executivas", root, "EventCycleExecutiveDecisionTrailSection", 420);
            CreateWebSection<ApplyQuestResultPanel>("Aplicar resultado da sessão Quest (mock)", root, "ApplyQuestSection", 200);
            CreateWebSection<HandoffToProducerPanel>("Handoff para produtor (gerar pedido / ver status)", root, "HandoffProducerSection", 220);
            CreateWebSection<OrderCommunicationPanel>("Comunicação operacional (thread por pedido)", root, "OrderCommunicationSection", 280);
            CreateWebSection<OrderScopePanel>("Escopo do pedido e confirmação operacional", root, "OrderScopeSection", 260);
            CreateWebSection<OrderReadinessPanel>("Prontidão para preparação / execução", root, "OrderReadinessSection", 200);
            CreateWebSection<OrderChecklistPanel>("Checklist operacional (resumo)", root, "OrderChecklistSection", 160);
            CreateWebSection<OrderExecutionPanel>("Status de execução do pedido", root, "OrderExecutionSection", 220);
            CreateWebSection<OrderFinalReportPanel>("Relatório final de execução", root, "OrderFinalReportSection", 260);
            CreateWebSection<OrderFinalAcceptancePanel>("Aceite final do hotel e encerramento do ciclo", root, "OrderFinalAcceptanceSection", 240);
            CreateWebSection<OpportunityPipelineView>("Pipeline comercial", root, "PipelineSection", 220);
            CreateWebSection<OpportunitySessionRelationView>("Oportunidade ↔ Sessão Quest", root, "OppSessionSection", 200);
            CreateWebSection<LeadListView>("Leads", root, "LeadsSection");
            CreateWebSection<OpportunityBoardView>("Oportunidades", root, "OpportunitiesSection");
            CreateWebSection<ProposalRecordView>("Propostas", root, "ProposalsSection");
            CreateWebSection<SessionRecordView>("Sessões Quest", root, "SessionsSection", 180);
            CreateWebSection<FollowUpTaskView>("Follow-ups", root, "FollowUpSection");
        }

        private void OnDestroy()
        {
            WebRuntimeContext.DataService = null;
            WebRuntimeContext.IndicatorsService = null;
        }

        private static void CreateTitle(Transform parent)
        {
            var go = new GameObject("WebTitle");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.sizeDelta = new Vector2(0, 50);
            var layoutElem = go.AddComponent<LayoutElement>();
            layoutElem.preferredHeight = 50;
            var text = go.AddComponent<Text>();
            text.text = WebTitle;
            text.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            text.fontSize = 26;
            text.alignment = TextAnchor.MiddleCenter;
        }

        private void CreateWebSection<T>(string sectionTitle, Transform parent, string sectionName, int preferredHeight = 140) where T : MonoBehaviour, IWebContentRoot
        {
            var section = new GameObject(sectionName);
            section.transform.SetParent(parent, false);
            var sectionRt = section.AddComponent<RectTransform>();
            sectionRt.sizeDelta = new Vector2(0, preferredHeight);
            var sectionLayoutElem = section.AddComponent<LayoutElement>();
            sectionLayoutElem.preferredHeight = preferredHeight;
            sectionLayoutElem.flexibleHeight = 0;

            var layout = section.AddComponent<VerticalLayoutGroup>();
            layout.spacing = 6;
            layout.padding = new RectOffset(20, 10, 10, 10);
            layout.childForceExpandHeight = false;
            layout.childForceExpandWidth = true;

            var bg = section.AddComponent<Image>();
            bg.color = new Color(0.92f, 0.94f, 0.98f, 1f);

            var label = new GameObject("Label");
            label.transform.SetParent(section.transform, false);
            var labelRt = label.AddComponent<RectTransform>();
            labelRt.sizeDelta = new Vector2(0, 24);
            var labelText = label.AddComponent<Text>();
            labelText.text = sectionTitle;
            labelText.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            labelText.fontSize = 18;
            labelText.fontStyle = FontStyle.Bold;

            var contentGo = new GameObject("Content");
            contentGo.transform.SetParent(section.transform, false);
            var contentRt = contentGo.AddComponent<RectTransform>();
            contentRt.sizeDelta = new Vector2(0, preferredHeight - 40);
            var contentLayout = contentGo.AddComponent<VerticalLayoutGroup>();
            contentLayout.spacing = 4;
            contentLayout.childForceExpandHeight = false;
            contentLayout.childForceExpandWidth = true;

            var listView = section.AddComponent<T>();
            listView.SetContentRoot(contentGo.transform);
        }

        private static Transform CreateScrollRoot(Transform canvas)
        {
            var go = new GameObject("ScrollView");
            go.transform.SetParent(canvas, false);
            var rt = go.AddComponent<RectTransform>();
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.offsetMin = Vector2.zero;
            rt.offsetMax = Vector2.zero;
            var scrollRect = go.AddComponent<ScrollRect>();
            scrollRect.horizontal = false;
            scrollRect.vertical = true;

            var viewport = new GameObject("Viewport");
            viewport.transform.SetParent(go.transform, false);
            var vpRt = viewport.AddComponent<RectTransform>();
            vpRt.anchorMin = Vector2.zero;
            vpRt.anchorMax = Vector2.one;
            vpRt.offsetMin = Vector2.zero;
            vpRt.offsetMax = Vector2.zero;
            viewport.AddComponent<Image>().color = new Color(1, 1, 1, 0.01f);
            viewport.AddComponent<Mask>().showMaskGraphic = false;

            var content = new GameObject("Content");
            content.transform.SetParent(viewport.transform, false);
            var cRt = content.AddComponent<RectTransform>();
            cRt.anchorMin = new Vector2(0, 1);
            cRt.anchorMax = Vector2.one;
            cRt.pivot = new Vector2(0.5f, 1f);
            cRt.sizeDelta = new Vector2(0, 0);
            var layout = content.AddComponent<VerticalLayoutGroup>();
            layout.spacing = 12;
            layout.padding = new RectOffset(20, 20, 20, 20);
            layout.childForceExpandHeight = false;
            layout.childForceExpandWidth = true;
            layout.childControlHeight = true;
            content.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;

            scrollRect.viewport = vpRt;
            scrollRect.content = cRt;
            return content.transform;
        }

        private static Transform CreateRootWithLayout(Transform parent)
        {
            var go = new GameObject("WebUIRoot");
            go.transform.SetParent(parent, false);
            var rt = go.AddComponent<RectTransform>();
            rt.anchorMin = new Vector2(0, 1);
            rt.anchorMax = Vector2.one;
            rt.pivot = new Vector2(0.5f, 1f);
            var layout = go.AddComponent<VerticalLayoutGroup>();
            layout.spacing = 12;
            layout.padding = new RectOffset(0, 0, 0, 0);
            layout.childForceExpandHeight = false;
            layout.childForceExpandWidth = true;
            layout.childControlHeight = true;
            return go.transform;
        }

        private static Canvas CreateCanvas()
        {
            var go = new GameObject("WebCanvas");
            var canvas = go.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvas.pixelPerfect = false;
            go.AddComponent<CanvasScaler>().uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            go.GetComponent<CanvasScaler>().referenceResolution = new Vector2(CanvasWidth, CanvasHeight);
            go.GetComponent<CanvasScaler>().matchWidthOrHeight = 0.5f;
            go.AddComponent<GraphicRaycaster>();
            var rt = go.GetComponent<RectTransform>();
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.one;
            rt.offsetMin = Vector2.zero;
            rt.offsetMax = Vector2.zero;
            return canvas;
        }
    }
}
