using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe temas visuais / direção estética disponíveis para o contexto atual.
    /// Permite aplicar tema ao projeto. Usa referências explícitas a containers (sem Find por nome).
    /// </summary>
    public class VisualThemeView : MonoBehaviour
    {
        private const string Title = "Temas Visuais / Direção Estética";
        private const string NenhumProjeto = "Nenhum projeto iniciado. Inicie um projeto para aplicar temas.";
        private const string Aplicar = "Aplicar";
        private const string Padrao = " (padrão)";
        private const string Cores = "Cores: ";
        private const string MoodLabel = "Mood: ";

        private AppSession _session;
        private IVisualThemeService _themeService;
        private Transform _themesRoot;
        private Font _font;

        private void Start()
        {
            _session = ServiceRegistry.Instance.Get<AppSession>();
            _themeService = ServiceRegistry.Instance.Get<IVisualThemeService>();
            if (_session != null)
                _session.OnSessionChanged += UpdateContent;

            _font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            BuildUI();
            UpdateContent();
        }

        private void OnDestroy()
        {
            if (_session != null)
                _session.OnSessionChanged -= UpdateContent;
        }

        private void BuildUI()
        {
            var layout = gameObject.GetComponent<VerticalLayoutGroup>();
            if (layout == null)
            {
                layout = gameObject.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 8;
                layout.padding = new RectOffset(12, 12, 12, 12);
                layout.childForceExpandHeight = false;
                layout.childForceExpandWidth = true;
            }

            var titleGo = new GameObject("Title");
            titleGo.transform.SetParent(transform, false);
            titleGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 22);
            var titleText = titleGo.AddComponent<Text>();
            titleText.text = Title;
            titleText.font = _font;
            titleText.fontSize = 16;
            titleText.fontStyle = FontStyle.Bold;

            _themesRoot = new GameObject("ThemesRoot").transform;
            _themesRoot.SetParent(transform, false);
            var le = _themesRoot.gameObject.AddComponent<LayoutElement>();
            le.preferredHeight = 200;
            var vlg = _themesRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            vlg.spacing = 6;
            vlg.childForceExpandHeight = false;
            vlg.childForceExpandWidth = true;
        }

        private void UpdateContent()
        {
            ClearChildren(_themesRoot);

            if (_themeService == null) return;

            var project = _session?.CurrentProject;
            IReadOnlyList<EventVisualTheme> themes;
            if (project != null)
                themes = _themeService.GetAvailableForProject(project);
            else
            {
                var templateId = _session?.SelectedTemplateId;
                var categoryId = _session?.SelectedCategoryId;
                if (!string.IsNullOrEmpty(templateId))
                    themes = _themeService.GetByTemplateId(templateId);
                else if (!string.IsNullOrEmpty(categoryId))
                    themes = _themeService.GetByCategoryId(categoryId);
                else
                    themes = new List<EventVisualTheme>();
            }

            if (project == null && themes.Count == 0)
            {
                AppendText(_themesRoot, NenhumProjeto);
                return;
            }

            if (project == null)
            {
                AppendText(_themesRoot, NenhumProjeto);
                foreach (var t in themes)
                    AppendThemeRow(_themesRoot, t, null);
                return;
            }

            foreach (var theme in themes)
                AppendThemeRow(_themesRoot, theme, theme.Id);
        }

        private void AppendThemeRow(Transform parent, EventVisualTheme theme, string themeIdForApply)
        {
            var row = new GameObject($"Theme_{theme.Id}");
            row.transform.SetParent(parent, false);
            var rowVlg = row.AddComponent<VerticalLayoutGroup>();
            rowVlg.spacing = 2;
            rowVlg.padding = new RectOffset(6, 4, 4, 4);
            rowVlg.childForceExpandHeight = false;
            rowVlg.childForceExpandWidth = true;
            row.AddComponent<Image>().color = new Color(1f, 1f, 1f, 0.5f);

            var line1 = new GameObject("Line1");
            line1.transform.SetParent(row.transform, false);
            var line1Hlg = line1.AddComponent<HorizontalLayoutGroup>();
            line1Hlg.spacing = 8;
            line1Hlg.childForceExpandWidth = false;
            line1Hlg.childForceExpandHeight = true;
            line1.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 20);

            var nameGo = new GameObject("Name");
            nameGo.transform.SetParent(line1.transform, false);
            nameGo.AddComponent<RectTransform>().sizeDelta = new Vector2(220, 18);
            var nameLE = nameGo.AddComponent<LayoutElement>();
            nameLE.preferredWidth = 220;
            nameLE.flexibleWidth = 1;
            var nameText = nameGo.AddComponent<Text>();
            nameText.text = theme.Name + (theme.IsDefault ? Padrao : "");
            nameText.font = _font;
            nameText.fontSize = 14;
            nameText.fontStyle = FontStyle.Bold;

            if (!string.IsNullOrEmpty(themeIdForApply))
            {
                var btnGo = new GameObject("ApplyBtn");
                btnGo.transform.SetParent(line1.transform, false);
                btnGo.AddComponent<RectTransform>().sizeDelta = new Vector2(70, 22);
                var btnLE = btnGo.AddComponent<LayoutElement>();
                btnLE.preferredWidth = 70;
                btnLE.preferredHeight = 22;
                var btn = btnGo.AddComponent<Button>();
                btnGo.AddComponent<Image>().color = new Color(0.5f, 0.4f, 0.65f, 1f);
                var btnTextGo = new GameObject("Text");
                btnTextGo.transform.SetParent(btnGo.transform, false);
                var btnTextRt = btnTextGo.AddComponent<RectTransform>();
                btnTextRt.anchorMin = Vector2.zero;
                btnTextRt.anchorMax = Vector2.one;
                btnTextRt.offsetMin = Vector2.zero;
                btnTextRt.offsetMax = Vector2.zero;
                var btnText = btnTextGo.AddComponent<Text>();
                btnText.text = Aplicar;
                btnText.font = _font;
                btnText.fontSize = 12;
                btnText.alignment = TextAnchor.MiddleCenter;
                btnText.color = Color.white;
                var idCapture = theme.Id;
                btn.onClick.AddListener(() => _session?.ApplyTheme(idCapture));
            }

            if (!string.IsNullOrEmpty(theme.Description))
            {
                var descGo = new GameObject("Description");
                descGo.transform.SetParent(row.transform, false);
                descGo.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
                var descText = descGo.AddComponent<Text>();
                descText.text = theme.Description;
                descText.font = _font;
                descText.fontSize = 11;
                descText.color = new Color(0.35f, 0.35f, 0.35f, 1f);
            }

            var moodLine = new GameObject("MoodLine");
            moodLine.transform.SetParent(row.transform, false);
            moodLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
            var moodText = moodLine.AddComponent<Text>();
            moodText.text = MoodLabel + (theme.Mood ?? "—");
            moodText.font = _font;
            moodText.fontSize = 11;

            var colorsLine = new GameObject("ColorsLine");
            colorsLine.transform.SetParent(row.transform, false);
            colorsLine.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 14);
            var colorsText = colorsLine.AddComponent<Text>();
            colorsText.text = Cores + (theme.PrimaryColor ?? "") + " / " + (theme.SecondaryColor ?? "") + " / " + (theme.AccentColor ?? "");
            colorsText.font = _font;
            colorsText.fontSize = 10;
            colorsText.color = new Color(0.4f, 0.4f, 0.4f, 1f);
        }

        private void AppendText(Transform parent, string text)
        {
            var go = new GameObject("TextLine");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 18);
            var t = go.AddComponent<Text>();
            t.text = text;
            t.font = _font;
            t.fontSize = 13;
        }

        private static void ClearChildren(Transform root)
        {
            if (root == null) return;
            for (var i = root.childCount - 1; i >= 0; i--)
                Object.Destroy(root.GetChild(i).gameObject);
        }
    }
}
