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

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Exibe e permite editar o briefing do cliente e parâmetros do evento (nome cliente, evento, convidados, orçamento alvo, mood, cores, elementos obrigatórios/evitar, observações).
    /// </summary>
    public class ClientBriefView : MonoBehaviour
    {
        private const string Title = "Briefing do Cliente / Parâmetros do Evento";
        private const string NenhumProjeto = "Nenhum projeto iniciado. Inicie um projeto para editar o briefing.";
        private const string Aplicar = "Aplicar briefing";

        private AppSession _session;
        private Transform _contentRoot;
        private InputField _clientNameInput;
        private InputField _eventNameInput;
        private InputField _guestCountInput;
        private InputField _budgetTargetInput;
        private InputField _moodInput;
        private InputField _colorsInput;
        private InputField _mustHaveInput;
        private InputField _avoidInput;
        private InputField _notesInput;
        private Font _font;

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

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

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

        private void BuildUI()
        {
            var layout = gameObject.GetComponent<VerticalLayoutGroup>();
            if (layout == null)
            {
                layout = gameObject.AddComponent<VerticalLayoutGroup>();
                layout.spacing = 6;
                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;

            _contentRoot = new GameObject("ContentRoot").transform;
            _contentRoot.SetParent(transform, false);
            var contentLe = _contentRoot.gameObject.AddComponent<LayoutElement>();
            contentLe.preferredHeight = 320;
            var contentVlg = _contentRoot.gameObject.AddComponent<VerticalLayoutGroup>();
            contentVlg.spacing = 4;
            contentVlg.childForceExpandHeight = false;
            contentVlg.childForceExpandWidth = true;

            _clientNameInput = AddRow(_contentRoot, "Cliente:");
            _eventNameInput = AddRow(_contentRoot, "Nome do evento:");
            _guestCountInput = AddRow(_contentRoot, "Convidados:");
            _budgetTargetInput = AddRow(_contentRoot, "Orçamento alvo (R$):");
            _moodInput = AddRow(_contentRoot, "Mood desejado:");
            _colorsInput = AddRow(_contentRoot, "Cores preferidas (separar por vírgula):");
            _mustHaveInput = AddRow(_contentRoot, "Elementos obrigatórios (separar por vírgula):");
            _avoidInput = AddRow(_contentRoot, "Elementos a evitar (separar por vírgula):");
            _notesInput = AddRow(_contentRoot, "Observações:", height: 40);

            var btnRow = new GameObject("ButtonRow");
            btnRow.transform.SetParent(transform, false);
            btnRow.AddComponent<RectTransform>().sizeDelta = new Vector2(0, 28);
            var btn = CreateButton(btnRow.transform, Aplicar, OnApplyClicked);
        }

        private InputField AddRow(Transform parent, string label, int height = 22)
        {
            var row = new GameObject("Row");
            row.transform.SetParent(parent, false);
            row.AddComponent<RectTransform>().sizeDelta = new Vector2(0, height);
            var rowHlg = row.AddComponent<HorizontalLayoutGroup>();
            rowHlg.spacing = 8;
            rowHlg.childForceExpandHeight = true;
            rowHlg.childForceExpandWidth = false;

            var labelGo = new GameObject("Label");
            labelGo.transform.SetParent(row.transform, false);
            var labelLe = labelGo.AddComponent<LayoutElement>();
            labelLe.preferredWidth = 180;
            labelLe.minWidth = 120;
            var labelText = labelGo.AddComponent<Text>();
            labelText.text = label;
            labelText.font = _font;
            labelText.fontSize = 12;

            var inputGo = new GameObject("Input");
            inputGo.transform.SetParent(row.transform, false);
            var inputLe = inputGo.AddComponent<LayoutElement>();
            inputLe.flexibleWidth = 1;
            inputLe.preferredWidth = 200;
            inputLe.preferredHeight = height - 2;
            var inputImage = inputGo.AddComponent<Image>();
            inputImage.color = new Color(1f, 1f, 1f, 0.95f);
            var inputField = inputGo.AddComponent<InputField>();

            var textGo = new GameObject("Text");
            textGo.transform.SetParent(inputGo.transform, false);
            var textRt = textGo.AddComponent<RectTransform>();
            textRt.anchorMin = Vector2.zero;
            textRt.anchorMax = Vector2.one;
            textRt.offsetMin = new Vector2(4, 2);
            textRt.offsetMax = new Vector2(-4, -2);
            var text = textGo.AddComponent<Text>();
            text.font = _font;
            text.fontSize = 12;
            text.supportRichText = false;
            inputField.textComponent = text;

            var placeholderGo = new GameObject("Placeholder");
            placeholderGo.transform.SetParent(inputGo.transform, false);
            var placeholderRt = placeholderGo.AddComponent<RectTransform>();
            placeholderRt.anchorMin = Vector2.zero;
            placeholderRt.anchorMax = Vector2.one;
            placeholderRt.offsetMin = new Vector2(4, 2);
            placeholderRt.offsetMax = new Vector2(-4, -2);
            var placeholderText = placeholderGo.AddComponent<Text>();
            placeholderText.text = "";
            placeholderText.font = _font;
            placeholderText.fontSize = 12;
            placeholderText.color = new Color(0.5f, 0.5f, 0.5f, 0.8f);
            inputField.placeholder = placeholderText;

            return inputField;
        }

        private static Button CreateButton(Transform parent, string label, UnityEngine.Events.UnityAction onClick)
        {
            var go = new GameObject("Btn");
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>().sizeDelta = new Vector2(160, 26);
            var le = go.AddComponent<LayoutElement>();
            le.preferredWidth = 160;
            le.preferredHeight = 26;
            var btn = go.AddComponent<Button>();
            go.AddComponent<Image>().color = new Color(0.3f, 0.5f, 0.35f, 1f);
            var textGo = new GameObject("Text");
            textGo.transform.SetParent(go.transform, false);
            var textRt = textGo.AddComponent<RectTransform>();
            textRt.anchorMin = Vector2.zero;
            textRt.anchorMax = Vector2.one;
            textRt.offsetMin = Vector2.zero;
            textRt.offsetMax = Vector2.zero;
            var text = textGo.AddComponent<Text>();
            text.text = label;
            text.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            text.fontSize = 12;
            text.alignment = TextAnchor.MiddleCenter;
            text.color = Color.white;
            btn.onClick.AddListener(onClick);
            return btn;
        }

        private void OnApplyClicked()
        {
            if (_session?.CurrentProject == null) return;
            var brief = ReadBriefFromInputs();
            _session.SetClientBrief(brief);
        }

        private ClientEventBrief ReadBriefFromInputs()
        {
            var brief = new ClientEventBrief();
            brief.ClientName = _clientNameInput != null ? (_clientNameInput.text ?? "").Trim() : "";
            brief.EventName = _eventNameInput != null ? (_eventNameInput.text ?? "").Trim() : "";
            int guestCount;
            brief.GuestCount = (_guestCountInput != null && int.TryParse(_guestCountInput.text?.Trim(), out guestCount) && guestCount >= 0) ? guestCount : 0;
            float budget;
            brief.EstimatedBudgetTarget = (_budgetTargetInput != null && float.TryParse(_budgetTargetInput.text?.Trim().Replace(",", "."), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out budget) && budget >= 0) ? budget : 0f;
            brief.PreferredMood = _moodInput != null ? (_moodInput.text ?? "").Trim() : "";
            brief.PreferredColors = ParseList(_colorsInput?.text);
            brief.MustHaveElements = ParseList(_mustHaveInput?.text);
            brief.AvoidElements = ParseList(_avoidInput?.text);
            brief.Notes = _notesInput != null ? (_notesInput.text ?? "").Trim() : "";
            return brief;
        }

        private static List<string> ParseList(string commaSeparated)
        {
            if (string.IsNullOrWhiteSpace(commaSeparated)) return new List<string>();
            return commaSeparated.Split(',')
                .Select(s => s.Trim())
                .Where(s => s.Length > 0)
                .ToList();
        }

        private void UpdateFromProject()
        {
            var project = _session?.CurrentProject;
            if (project == null)
            {
                SetInputsEnabled(false);
                if (_eventNameInput != null) _eventNameInput.text = "";
                if (_clientNameInput != null) _clientNameInput.text = "";
                if (_guestCountInput != null) _guestCountInput.text = "";
                if (_budgetTargetInput != null) _budgetTargetInput.text = "";
                if (_moodInput != null) _moodInput.text = "";
                if (_colorsInput != null) _colorsInput.text = "";
                if (_mustHaveInput != null) _mustHaveInput.text = "";
                if (_avoidInput != null) _avoidInput.text = "";
                if (_notesInput != null) _notesInput.text = "";
                return;
            }

            SetInputsEnabled(true);
            var b = project.ClientBrief;
            if (b != null)
            {
                _clientNameInput.text = b.ClientName ?? "";
                _eventNameInput.text = b.EventName ?? "";
                _guestCountInput.text = b.GuestCount > 0 ? b.GuestCount.ToString() : "";
                _budgetTargetInput.text = b.EstimatedBudgetTarget > 0 ? b.EstimatedBudgetTarget.ToString("F0") : "";
                _moodInput.text = b.PreferredMood ?? "";
                _colorsInput.text = b.PreferredColors != null ? string.Join(", ", b.PreferredColors) : "";
                _mustHaveInput.text = b.MustHaveElements != null ? string.Join(", ", b.MustHaveElements) : "";
                _avoidInput.text = b.AvoidElements != null ? string.Join(", ", b.AvoidElements) : "";
                _notesInput.text = b.Notes ?? "";
            }
            else
            {
                _clientNameInput.text = "";
                _eventNameInput.text = "";
                _guestCountInput.text = "";
                _budgetTargetInput.text = "";
                _moodInput.text = "";
                _colorsInput.text = "";
                _mustHaveInput.text = "";
                _avoidInput.text = "";
                _notesInput.text = "";
            }
        }

        private void SetInputsEnabled(bool enabled)
        {
            if (_clientNameInput != null) _clientNameInput.interactable = enabled;
            if (_eventNameInput != null) _eventNameInput.interactable = enabled;
            if (_guestCountInput != null) _guestCountInput.interactable = enabled;
            if (_budgetTargetInput != null) _budgetTargetInput.interactable = enabled;
            if (_moodInput != null) _moodInput.interactable = enabled;
            if (_colorsInput != null) _colorsInput.interactable = enabled;
            if (_mustHaveInput != null) _mustHaveInput.interactable = enabled;
            if (_avoidInput != null) _avoidInput.interactable = enabled;
            if (_notesInput != null) _notesInput.interactable = enabled;
        }
    }
}
