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

namespace EventsAppQuest.Web.Producer.Presentation
{
    /// <summary>
    /// Controlador do dashboard do produtor/prestador: pedidos, escopo, requisitos, status, observações.
    /// Camada isolada; não altera Quest nem CRM do hotel.
    /// </summary>
    public class ProducerDashboardController : MonoBehaviour
    {
        private const string Title = "Painel Produtor / Prestador — Pedidos e Escopo";
        private const int CanvasWidth = 1920;
        private const int CanvasHeight = 1080;

        private void Awake()
        {
            ProducerRuntimeContext.DataService = new MockProducerDataService();
        }

        private void Start()
        {
            var canvas = CreateCanvas();
            var scrollRoot = CreateScrollRoot(canvas.transform);
            var root = CreateRoot(scrollRoot);
            CreateTitle(root);
            CreateProducerSection<ProducerOrderListView>("Pedidos recebidos", root, "OrdersSection", 120);
            CreateProducerSection<ProducerOrderDetailsView>("Escopo do evento / Origem do pedido", root, "DetailsSection", 220);
            CreateProducerSection<ProducerAcceptancePanel>("Aceite / Revisão do pedido", root, "AcceptanceSection", 180);
            CreateProducerSection<ProducerOrderCommunicationView>("Comunicação com o hotel (thread por pedido)", root, "CommunicationSection", 260);
            CreateProducerSection<ProducerScopeRevisionView>("Escopo e confirmação operacional", root, "ScopeRevisionSection", 260);
            CreateProducerSection<ProducerReadinessView>("Prontidão para execução", root, "ReadinessSection", 220);
            CreateProducerSection<ProducerPreparationChecklistView>("Checklist operacional e confirmação de preparação", root, "ChecklistSection", 280);
            CreateProducerSection<ProducerExecutionTrackingView>("Execução operacional (status e acompanhamento)", root, "ExecutionTrackingSection", 320);
            CreateProducerSection<ProducerFinalReportView>("Conclusão operacional e relatório final", root, "FinalReportSection", 280);
            CreateProducerSection<ProducerRequirementListView>("Requisitos", root, "RequirementsSection", 140);
            CreateProducerSection<ProducerStatusView>("Status e atualizações", root, "StatusSection", 160);
            CreateProducerSection<ProducerExecutionNotesView>("Observações", root, "NotesSection", 120);
        }

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

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

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

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

            var bg = section.AddComponent<Image>();
            bg.color = new Color(0.96f, 0.97f, 0.95f, 1f);

            var label = new GameObject("Label");
            label.transform.SetParent(section.transform, false);
            var labelRt = label.AddComponent<RectTransform>();
            labelRt.sizeDelta = new Vector2(0, 22);
            var labelText = label.AddComponent<Text>();
            labelText.text = sectionTitle;
            labelText.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            labelText.fontSize = 16;
            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 - 36);
            var contentLayout = contentGo.AddComponent<VerticalLayoutGroup>();
            contentLayout.spacing = 4;
            contentLayout.childForceExpandHeight = false;
            contentLayout.childForceExpandWidth = true;

            var view = section.AddComponent<T>();
            view.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 CreateRoot(Transform parent)
        {
            var go = new GameObject("Root");
            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("ProducerCanvas");
            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;
        }
    }
}
