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

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Controlador da vista principal da camada Web (dashboard mock).
    /// Monta canvas e secções (Leads, Oportunidades, Propostas, Sessões, Follow-ups).
    /// Não altera Quest nem AppSession.
    /// </summary>
    public class WebDashboardController : MonoBehaviour
    {
        private const string WebTitle = "Web Hotel / Espaço — CRM";
        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);
        }

        private void Start()
        {
            var canvas = CreateCanvas();
            var root = CreateRootWithLayout(canvas.transform);
            CreateTitle(root);
            CreateWebSection<LeadListView>("Leads", root, "LeadsSection");
            CreateWebSection<OpportunityBoardView>("Oportunidades", root, "OpportunitiesSection");
            CreateWebSection<ProposalRecordView>("Propostas", root, "ProposalsSection");
            CreateWebSection<SessionRecordView>("Sessões Quest", root, "SessionsSection");
            CreateWebSection<FollowUpTaskView>("Follow-ups", root, "FollowUpSection");
        }

        private void OnDestroy()
        {
            WebRuntimeContext.DataService = 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 = 28;
            text.alignment = TextAnchor.MiddleCenter;
        }

        private void CreateWebSection<T>(string sectionTitle, Transform parent, string sectionName) where T : MonoBehaviour, IWebContentRoot
        {
            var section = new GameObject(sectionName);
            section.transform.SetParent(parent, false);
            var sectionRt = section.AddComponent<RectTransform>();
            sectionRt.sizeDelta = new Vector2(0, 140);
            var sectionLayoutElem = section.AddComponent<LayoutElement>();
            sectionLayoutElem.preferredHeight = 140;
            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, 100);
            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 CreateRootWithLayout(Transform canvas)
        {
            var go = new GameObject("WebUIRoot");
            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 layout = go.AddComponent<VerticalLayoutGroup>();
            layout.spacing = 16;
            layout.padding = new RectOffset(20, 20, 20, 20);
            layout.childControlHeight = true;
            layout.childControlWidth = true;
            layout.childForceExpandHeight = false;
            layout.childForceExpandWidth = 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;
        }
    }
}
